算起来,mp也用了两年多了,总体上还是非常舒服的,导致我现在都不想写sql了,网络上教程很多,这里只记录我项目中感觉较为好用的功能

什么是MybatisPlus

MyBatis-Plus(简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

愿景是成为Mybatis最好的搭档,就像魂斗罗中的1P、2P,基友搭配,效率翻倍

为什么选择它

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作

  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求

  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题

  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作

  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )

  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用

  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询

  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库

  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询

  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

快速开始

可以使用Spring Initializer(opens new window)快速初始化一个SpringBoot 工程

  1. 添加父工程(Spring Boot Starter)
    1
    2
    3
    4
    5
    6
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5+ 版本</version>
    <relativePath/>
    </parent>
  2. 引入依赖
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    // spring-boot-starter、spring-boot-starter-test、mybatis-plus-boot-starter、h2
    <dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>
    <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>最新版本</version>
    </dependency>
    <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
    </dependency>
    </dependencies>
  3. 添加配置(application.yml)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # DataSource Config
    spring:
    datasource:
    driver-class-name: org.h2.Driver
    schema: classpath:db/schema-h2.sql
    username: root
    password: test
    sql:
    init:
    schema-locations: classpath:db/schema-h2.sql
    data-locations: classpath:db/data-h2.sql
  4. 添加扫描注解(@MapperScan)
    1
    2
    3
    4
    5
    6
    7
    @SpringBootApplication
    @MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
    public class Application {
    public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
    }
    }
  5. 测试代码(使用Lombok简化代码)
  • 实体类
    1
    2
    3
    4
    5
    6
    7
    @Data
    public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
    }
  • mapper接口
    1
    2
    public interface UserMapper extends BaseMapper<User> {
    }
  • 编写测试类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @SpringBootTest
    public class SampleTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
    System.out.println(("----- selectAll method test ------"));
    List<User> userList = userMapper.selectList(null);
    Assert.assertEquals(5, userList.size());
    userList.forEach(System.out::println);
    }
    }

    selectList()不填写表示无参数

  • 控制台输出
    1
    2
    3
    4
    5
    User(id=1, name=Jone, age=18, email=test1@baomidou.com)
    User(id=2, name=Jack, age=20, email=test2@baomidou.com)
    User(id=3, name=Tom, age=28, email=test3@baomidou.com)
    User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
    User(id=5, name=Billie, age=24, email=test5@baomidou.com)

配置日志(bootstrap.yml)

1
2
3
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

自动填充

一般来说,代码中create_time、update_time、create_user等字段希望是自动化完成,不希望手动更新
阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上!而且需要自动化!

  1. 表中添加字段create_time、update_time
  2. 删除数据库中配置的更新属性
  3. 实体中添加@TableField注解
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /**
    * 创建人
    */
    @ApiModelProperty(value="创建人")
    @TableField(fill = FieldFill.INSERT)
    private String createName;
    /**
    * 创建时间
    */
    @ApiModelProperty(value="创建时间")
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;
  4. 添加处理器来处理该注解
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    /**
    * 自定义字段填充类
    *
    * @author Manxin
    * @date 2023-03-28 16:06:47
    */

    @Component
    public class MyDateObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
    User user = SecurityUtils.getUser();
    this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
    this.setFieldValByName("createId", user.getId(), metaObject);
    this.setFieldValByName("createName", user.getRealname(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {

    }
    }
  5. 测试观察数据库即可

乐观锁

乐观锁:故名思议十分乐观,它总是认为不会出现问题,无论干什么不去上锁!如果出了问题,再次更新值测试
悲观锁:故名思议十分悲观,它总是认为总是出现问题,无论干什么都会上锁!再去操作!

乐观锁实现的方式

取出记录时,获取当前version
更新时,带上这个version
执行更新时, set version = newVersion where version = oldVersion
如果version不对,就更新失败

测试乐观锁插件

  1. 数据库添加version字段
  2. 实体类添加version字段
  3. 注册使用
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @MapperScan("com.mx.mapper")//扫描mapper文件夹
    @EnableTransactionManagement
    @Configuration//配置类
    public class MyBatisPlusConfig {

    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
    return new OptimisticLockerInterceptor();
    }
    }

  4. 测试效果
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    //乐观锁-成功
    @Test
    public void versionTest(){
    User user = userMapper.selectById(1L);
    user.setName("满心");
    user.setEmail("manxin@lovelu.top");
    userMapper.updateById(user);
    }

    //乐观锁失败----多线程
    @Test
    public void OptimisticLockerTest(){
    User user = userMapper.selectById(1L);
    user.setName("满心");
    user.setEmail("manxin@lovelu.top");

    //模拟另外一个线程执行了插队操作
    User user2 = userMapper.selectById(1L);
    user.setName("满心2");
    user.setEmail("manxin@lovelu.top");
    userMapper.updateById(user2);
    userMapper.updateById(user);
    }

逻辑删除

物理删除:从数据库中直接移除
逻辑删除:在数据库中没有被移除,而是通过一个变量让他无效!delete = 0 —> delete = 1

管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!

  1. 数据库添加deleted字段
  2. 实体中添加deleted属性
  3. 配置逻辑删除(bootstrap.yml)
    1
    2
    3
    #配置逻辑删除  1 删除  0 未删除
    mybatis-plus.global-config.db-config.logic-delete-value=1
    mybatis-plus.global-config.db-config.logic-not-delete-value=0

条件构造器(重要)

可以使用QueryWrapperLambdaQueryWrapper两种,我比较习惯使用后者(两者区别,后者对应的是实体字段,前者是数据库字段),具体可以看下面例子

  1. eg(QueryWrapper)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @Test
    public void queryWrapperTest(){
    //查询name不为空的用户,并且邮箱不为空的用户,年龄大于18
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper
    .isNotNull("name")
    .isNotNull("email")
    .ge("age",18);
    userMapper.selectList(wrapper).forEach(System.out::println);

    }
  2. eg(LambdaQueryWrapper)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @Test
    public void LambdaQueryWrapperTest(){
    //查询name不为空的用户,并且邮箱不为空的用户,年龄大于18
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper
    .isNotNull(User::getName)
    .isNotNull(User::getEmail)
    .ge(User::getAge,18);
    userMapper.selectList(wrapper).forEach(System.out::println);
    }

代码生成器

AutoGenerator是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class Generator{
public static void main(String[] args){
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();

// 2、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("满心");
gc.setOpen(false); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setIdType(IdType.ID_WORKER_STR); //主键策略
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
gc.setSwagger2(true);//开启Swagger2模式

mpg.setGlobalConfig(gc);

// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mx?useUnicode=true&characterEncoding=utf-8&useSSL=false");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);

// 4、包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("mx");
pc.setParent("com");
pc.setController("controller");
pc.setEntity("pojo");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);

// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
//strategy.setInclude("pdx_\\w*");//设置要映射的表名
strategy.setInclude("mx_download");//设置要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setTablePrefix("i_");//设置表前缀不生成

strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作

strategy.setRestControllerStyle(true); //restful api风格控制器
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

mpg.setStrategy(strategy);

// 6、执行
mpg.execute();
}
}