MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。同类框架:JPA、tk-mapper、MyBatisPlus。
官方文档地址:https://baomidou.com/
特性:
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
建pom:
添加pom依赖,注意:引入 MyBatis-Plus 之后请不要再次引入 MyBatis 以及 MyBatis-Spring,以避免因版本差异导致的问题。
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.0.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
dependencies>
写properties
# mysql 5
spring.datasource.username=root
spring.datasource.password=12345
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# mysql 8
#spring.datasource.username=root
#spring.datasource.password=root
#spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
mapper接口
/**
* 在对应的mapper上面继承基本的类 BaseMapper
* 添加注解@Repository或者@Mapper表示是持久层
*/
@Repository
public interface UserMapper extends BaseMapper<User> {
//所有的CRUD操作都已经编写完成了
//不需要像以前那样配置一大堆文件了
}
注意点: 要扫描mapper下的所有接口
@MapperScan("com.ui.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
测试
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
//查询全部用户
//参数是一个wrapper ,条件构造器,这里先不用,null
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
//测试插入
@Test
void testInsert(){
User user = new User();
user.setName("Java");
user.setAge(3);
user.setEmail("[email protected]");
int result = userMapper.insert(user);
System.out.println(result);//受影响的行数
System.out.println(user);//发现id会自动添加
}
结果
注意:数据库帮我们生成了id,数据库插入id的默认值为:全局唯一id.
主键生成方式
public enum IdType {
AUTO(0),//数据库id自增
NONE(1),//未设置主键
INPUT(2),//手动输入
ID_WORKER(3),//默认的全局id
UUID(4),//全局唯一的id uuid
ID_WORKER_STR(5);// ID_WORKER的字符串表示法
}
测试自增
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
我们需要配置主键自增:
1.实体类字段上增加@TableId(type = IdType.AUTO)
2.数据库字段一定要是自增的
测试结果
@Test
void testInsert(){
User user = new User();
user.setName("Java1");
user.setAge(13);
user.setEmail("[email protected]");
int result = userMapper.insert(user);
System.out.println(result);//受影响的行数
System.out.println(user);//发现id会自动添加
}
//测试更新
@Test
void testUpdate(){
//通过条件自动拼接sql
User user = new User();
user.setId(5L);
user.setName("Java");
userMapper.updateById(user);//注意这里参数是一个对象,不是id
}
方式一:数据库级别(工作中不允许修改数据库表)
ALTER TABLE `user`
ADD COLUMN `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间' AFTER `email`,
ADD COLUMN `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间' AFTER `create_time`;
注意:导入 SQL 时出现 Invalid default value for ‘create_time’ 报错解决方法
这个错误的主要原因,是因为给了时间字段的列默认值一个 CURRENT_TIMESTAMP 默认值,而这个默认值在低版本的 MySQL 中是不支持的,因此就出现了题目中的这个报错。
所以重装 MySQL 数据库,版本选择 5.7 或者 5.7 以上版本,或者将默认值改为null。
2.再次测试插入方法,我们需要先把实体类同步
private Date createTime;
private Date updateTime;
方式二:代码级别
//字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill...");
//setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill...");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
乐观锁:它认为不会出现问题,无论干什么不会去上锁,出现问题,再次更新测试
悲观锁:它认为总会出现问题,无论干什么都会上锁,再去操作
乐观锁实现方式:
乐观锁过程:
查询获得版本号 version=1
--A
update user set name ="abc",version = version +1
where id = 2 and version = 1
--B线程抢先完成修改,这是version=2,会导致A修改失败
update user set name ="abc",version = version +1
where id = 2 and version = 1
测试MP的乐观锁插件
@Version //乐观锁注解
private Integer version;
@Configuration //配置类
@EnableTransactionManagement
public class MyBatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
//测试乐观锁成功
@Test
public void testOptimisticLocker(){
//1.查询用户信息
User user = userMapper.selectById(1L);
//2.修改用户信息
user.setName("potato");
user.setEmail("[email protected]");
//3.执行更新操作
userMapper.updateById(user);
}
//测试乐观锁失败
@Test
public void testOptimisticLocker2(){
//线程1.
User user = userMapper.selectById(1L);
user.setName("potato111");
user.setEmail("[email protected]");
//模拟另一个线程执行了插队操作
User user2 = userMapper.selectById(1L);
user2.setName("potato111222");
user2.setEmail("[email protected]");
userMapper.updateById(user2);
//自旋锁来多次尝试提交
userMapper.updateById(user);//如果没有乐观锁,就会覆盖
}
//测试查询
@Test
void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
//测试批量查询
@Test
void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
//测试条件查询 map(后面用warpper)
@Test
void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
//自定义要查询的条件
map.put("name", "Jack");
map.put("age", "20");
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
1.原始的 limit 进行分页
2.pageHelper 第三方插件
3.MP也内置了分页插件
使用:
@Configuration //配置类
@EnableTransactionManagement
@MapperScan("com.potato.mapper") //扫描mapper包 @MapperScan("com.potato.mapper")
public class MyBatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
//设置请求页面大于最大页后操作,true调回到首页,false继续请求,默认false
//paginationInterceptor.setOverflow(false)
//设置最大单页限制数量,默认500条,-1不受限制
//paginationInterceptor.setLimit(500)
//开启count的join优化,只针对部分left join
//默认就够用了,不够再设置
return new PaginationInterceptor();
}
}
测试分页查询
//测试分页查询
@Test
void testPage(){
//参数1:当前页 参数2:页面大小
Page<User> page = new Page<>(1,5);//第1页,每页5个
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());//总数
}
//测试删除
@Test
void testDeleteById(){
userMapper.deleteById(1L);
}
//批量删除
void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1L,2L,3L));
}
//通过map删除
void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name", "Java");
userMapper.deleteByMap(map);
}
物理删除:从数据库中直接移除
逻辑删除:在数据中没有移除,而是通过一个变量来让它失效,deleted=0 --> deleted=1
目的: 防止数据的丢失,类似于回收站。
测试:
1、在数据表中增加一个deleted字段,默认为0
2、实体类中增加属性
@TableLogic //逻辑删除
private Integer deleted;
//逻辑删除
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
#配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
//测试逻辑删除
@Test
void testDeleteById1(){
userMapper.deleteById(1L);
}
本质是更新操作。
//测试查询
@Test
void testSelectById(){
User user = userMapper.selectById(2L);
System.out.println(user);
}
在开发中,会遇到慢sql,慢查询,MP也提供了性能分析插件,如果超过这个时间就停止运行。
作用: 性能分析拦截器,用于输出每条SQL语句及其执行时间。
//SQL执行效率插件
@Bean
@Profile({"dev","test"})// 设置dev test环境开启,保证效率
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(30);//设置sql执行的最大时间,如果超过了就不执行
performanceInterceptor.setFormat(true);//是否格式化
return performanceInterceptor;
}
application.properties 设置开发环境或测试环境
#设置开发环境
spring.profiles.active=dev
写一些复杂的sql就可以使用这个来替代。
@Test
void contextLoads() {
//查询name不为空且邮箱不为空的用户,年龄大于等于12岁
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.isNotNull("name")
.isNotNull("email")
.ge("age",12); //大于等于
userMapper.selectList(wrapper).forEach(System.out::println);//和刚才用的map对比一下
}
@Test
void test2(){
//查询名字
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","Java");
//查询一个数据,出现多个结果使用List或Map
User user = userMapper.selectOne(wrapper);
System.out.println(user);
}
@Test
void test3(){
//查询年龄在20-30岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30);//区间
Integer integer = userMapper.selectCount(wrapper);//查询结果数
System.out.println(integer);
}
@Test
void test4(){
//左和右 %e%
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.notLike("name","e")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);//查询结果数
maps.forEach(System.out::println);
}
@Test
void test5(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
//id在子查询中查询出来
wrapper.inSql("id","select id from user where id<3");
List<Object> objects = userMapper.selectObjs(wrapper);//查询结果数
objects.forEach(System.out::println);
}
//排序
@Test
void test6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
//通过id进行排序
wrapper.orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.6.0version>
<relativePath/>
parent>
<groupId>com.uigroupId>
<artifactId>autoartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>autoname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.0version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.4.0version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
3.写application.properties
# mysql 5
spring.datasource.username=root
spring.datasource.password=110120
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
#设置开发环境
spring.profiles.active=dev
#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
4.代码生成器
@Test
void contextLoads() {
//构建一个代码生成器
AutoGenerator mpg = new AutoGenerator();
//1.全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
System.out.println(projectPath);
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("yinan");
gc.setOpen(false);//是否打开输出目录,默认true
gc.setFileOverride(false);//是否覆盖已有文件,默认false
gc.setServiceName("%sService");//service命名方式,去Service的I前缀。默认值:null 例如:%sBusiness 生成 UserBusiness
gc.setIdType(IdType.ASSIGN_ID);//全局唯一id,采用雪花算法。默认:null
gc.setDateType(DateType.ONLY_DATE);//设置日期类型:只显示日期,默认TIME_PACK
// gc.setSwagger2(true);//实体属性 Swagger2 注解,默认false
mpg.setGlobalConfig(gc);
//2.设置数据源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("110120");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
//3.包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");
pc.setParent("com.ui");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//4.策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user");//设置要映射的表名(数据库中的表,可以一次写多个表)
strategy.setNaming(NamingStrategy.underline_to_camel);//下划线转驼峰命名
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);//自动lombok
strategy.setRestControllerStyle(true);//RestController
strategy.setLogicDeleteFieldName("deleted");//逻辑删除字段,对应数据库表的字段deleted
strategy.setControllerMappingHyphenStyle(true);//localhost:8080/hello_id_2
//自动填充配置
TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT);//创建时间
TableFill gmtModified = new TableFill("update_time", FieldFill.INSERT_UPDATE);//修改时间
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
//乐观锁
strategy.setVersionFieldName("version");
mpg.setStrategy(strategy);
mpg.execute();//执行
}
@MapperScan("com.ui.blog.mapper")
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.3.4version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
<version>2.2version>
dependency>
@Test
void test(){
String projectPath = System.getProperty("user.dir");
System.out.println(projectPath); //获取当前目录
DataSourceConfig dataSourceConfig = new DataSourceConfig.Builder("jdbc:postgresql://localhost:5432/PatientDB", "root", "999")
.dbQuery(new PostgreSqlQuery())
.typeConvert(new PostgreSqlTypeConvert())
.keyWordsHandler(new PostgreSqlKeyWordsHandler())
.build();
GlobalConfig globalConfig = new GlobalConfig.Builder()
.fileOverride()
.outputDir(projectPath + "/src/main/java")
.author("yinan")
.dateType(DateType.TIME_PACK)
.commentDate("yyyy-MM-dd")
.build();
PackageConfig packageConfig = new PackageConfig.Builder()
.parent("com.ui")
.moduleName("sys")
.entity("do")
.service("service")
.serviceImpl("service.impl")
.mapper("mapper")
.controller("controller")
.other("other")
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, projectPath + "/src/main/resources/mapper"))
.build();
StrategyConfig strategyConfig = new StrategyConfig.Builder()
.addTablePrefix("rtc_")
.entityBuilder()
.superClass(BaseDO.class)
.disableSerialVersionUID()
// .enableChainModel()
.enableLombok()
.enableRemoveIsPrefix()
// .enableTableFieldAnnotation()
//.enableActiveRecord()
// .versionColumnName("version")
// .versionPropertyName("version")
// .logicDeleteColumnName("deleted")
// .logicDeletePropertyName("deleteFlag")
.naming(NamingStrategy.underline_to_camel)
.columnNaming(NamingStrategy.underline_to_camel)
// .addSuperEntityColumns("id", "creation_time", "creator_user_id", "last_modification_time", "last_modifier_user_id")
// .addIgnoreColumns("age")
// .addTableFills(new Column("create_time", FieldFill.INSERT))
// .addTableFills(new Property("updateTime", FieldFill.INSERT_UPDATE))
.idType(IdType.AUTO)
.formatFileName("%sDO")
.build();
AutoGenerator generator = new AutoGenerator(dataSourceConfig);
generator.strategy(strategyConfig);
generator.global(globalConfig);
generator.packageInfo(packageConfig);
generator.execute();
}
}
详细注释看官网:https://baomidou.com/pages/981406/