Mybatis-Plus

32 阅读11分钟

注:本篇内容图片丢失,可以参考官网进行学习,有时间可能会补上图片

1. 简介

官网:mp.baomidou.com/

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

特性:

  1. 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  2. 损耗小:启动即会自动注入基本 CRUD ,性能基本无损耗,直接面向对象操作
  3. 强大的 CRUD 操作,内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  4. 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需担心字段写错
  5. 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  6. 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  7. 支持自定义全局通用操作:支持全局通用方法注入(Write once, use anywhere)
  8. 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper、Model、Service、Controller 层代码,支持模板引擎,更有超多自定义配置等着使用
  9. 内置分页插件:基于 Mybatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  10. 分页插件支持多种数据库:支持 MySql、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  11. 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  12. 内置全局拦截插件:提供全表 delete、update 操作智能分析阻断,也可自定义拦截规则,预防误操作

2. 快速使用

快速使用官网:mp.baomidou.com/guide/quick…

  1. 新建数据库 mybatis_plus

  2. 创建user 表,插入数据

    CREATE DATABASE mybatis_plus
    ​
    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)
    );
    ​
    DELETE FROM USER;
    ​
    INSERT INTO USER (id, NAME, age, email) VALUES
    (1, 'Jone', 18, 'test1@baomidou.com'),
    (2, 'Jack', 20, 'test2@baomidou.com'),
    (3, 'Tom', 28, 'test3@baomidou.com'),
    (4, 'Sandy', 21, 'test4@baomidou.com'),
    (5, 'Billie', 24, 'test5@baomidou.com');
    
  3. 导入 mybatis-plus 依赖

            <!--导入 mybatis-plus 依赖-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.3.1.tmp</version>
            </dependency>
            <!--连接数据驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
    
  4. 创建表的实体类

    使用了 lombok 插件,使用前需要在 setting -- plugs 里面下载,然后在 pom.xml 中导入依赖

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
    ​
        private Long id;
        private String name;
        private  Integer age;
        private String email;
    }
    
  5. 创建 UserMapper 接口

    // 在对应的 Mapper 上面继承类 BaseMpper
    @Mapper
    public interface UserMapper extends BaseMapper<User> {
        // 所有的 CRUD 操作都已经编写完了
        // 不用使用配置文件
    }
    

    这个创建好之后需要在主启动类上加上扫描注解

    // 扫描 mapper 文件夹
    @MapperScan("com.example.mapper")
    
  6. 测试运行

    @SpringBootTest
    class MybatisPlusQuitestartApplicationTests {
        // 继承了 BaseMapper,所有的方法都来自父类
        // 也可以自己扩展方法
        @Autowired
        private UserMapper userMapper;
        @Test
        void contextLoads() {
    //        参数时一个 Wrapper,条件构造器,这里先不用,使用null
            // 查询所有用户
            List<User> users = userMapper.selectList(null);
            users.forEach(System.out::println);
        }
    }
    

3. 配置日志

由于我们使用了 mybatis-plus后,所有的 sql 语句是不可见的,可以使用 日志来查看;在开发过程中可以使用日志查看,但是上线时尽量去掉,否则会影响执行效率(只是尽量建议 )。

  1. 首先需要配置日志
# 配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  1. 运行测试输出

4. 主键生成策略

  1. 编写插入数据的测试

        @Test
        public void insert(){
            User user = new User();
            user.setName("张三");
            user.setAge(20);
            user.setEmail("1111@qq.com");
            int result = userMapper.insert(user);
            System.out.println(result);
        }
    
  2. 查看日志输出结果

    在上面没有对 id 字段进行设置

  • 运行结果,自动生成 id 值:
  • 生成策略:

雪花算法:snowflake 是 Twitter 开源的分布式 ID 生成算法,结果是一个 long 型的 id,其核心思想是:使用 41bit 作为毫秒数,10bit 作为机器的 id(5个bit 是数据中心,5 个bit 的机器 id),12 bit 作为毫秒内的流水号(意味者每个节点在毫秒可以产生 4096个id),最后还有一个符号位,永远是 0。可以保证几乎全球唯一。

ID_WORKER 默认,雪花算法

  • 在创建的实体类的 id 属性上添加属性,这个id可以传值 T

    @TableId
    private Long id;
    

    在这里默认的是 ID_WORKER

@TableId(type = IdType.ID_WORKER)
private Long id;

主键自增

配置主键自增:

  1. 实体类字段上:@TableId(type = IdType.AUTO)
  2. 数据库的字段必须是自增的,否则会报错

其他

public enum IdType {
    AUTO(0),	// 数据库id自增
    NONE(1),	// 未设置主键
    INPUT(2),	// 手动输入,需要自己配置 id
    ID_WORKER(3),	// 默认的全局 id
    ID_WORKER_STR(3),	// ID_WORKER 的字符串表示
    UUID(4);	// 全局唯一 id
}

5. CRUD 扩展操作

5.1 插入操作

上面

5.2 更新操作

    @Test
    public void testUpdate(){
        User user = new User();
        // 通过条件自动拼接动态 sql
        user.setId(1L);
        user.setName("张");
        user.setAge(2);
        user.setEmail("1111@qq.co");
        // 注意: updateById 但是参数是一个对象
        int i = userMapper.updateById(user);
        System.out.println(i);
    }
  • 所有的 sql 都是动态配置的

5.3 自动填充

创建时间、修改时间,这些操作都是自动化完成的,不要手动更新

阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modified 几乎所有的表都要配置上,而且需要自动化

  • 方式一:数据库级别

    不建议使用

    1. 在表中新增字段:create_time、update_time

      mysql 5.7 以上可以勾选自动更新

  • 方式二:代码级别

    1. 实体类字段属性上需要增加注解

      // 字段添加填充内容
      @TableField(fill = FieldFill.INSERT)
      private Date createTime;
      @TableField(fill = FieldFill.INSERT_UPDATE)
      private Date updateTime;
      
    2. 编写处理器来处理这个注解

      @Slf4j
      @Component  // 加到 IOC 容器中
      public class MyDataHandle 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("update insert fill ......");
              this.setFieldValByName("updateTime",new Date(),metaObject);
          }
      }
      
    3. 测试运行

      插入修改操作的话数据会自动填充上

5.4 查询操作

    // 根据 id 查询一个
    @Test
    public void testSelectById(){
        User user = userMapper.selectById(1L);
        System.out.println(user);
    }
    // 根据一组 id 查询批量数据
    @Test
    public void testSelectByBatchId(){
        List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
        users.forEach(System.out::println);
    }
    // 根据 map 查询
    @Test
    public void testSelectByMapper(){

        HashMap<String, Object> map = new HashMap<>();
        // 要注意泛型使用 <String, Object>
        //List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
        map.put("age",20);
        map.put("email","test2@baomidou.com");
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);
    }	

5.5 分页查询

分页在网站中使用的非常多

使用

  1. 配置拦截器

    //Spring boot方式
    @Configuration
    @MapperScan("com.baomidou.cloud.service.*.mapper*")
    public class MybatisPlusConfig {
    
        // 旧版
        @Bean
        public PaginationInterceptor paginationInterceptor() {
            PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
            // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
            // paginationInterceptor.setOverflow(false);
            // 设置最大单页限制数量,默认 500 条,-1 不受限制
            // paginationInterceptor.setLimit(500);
            // 开启 count 的 join 优化,只针对部分 left join
            paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
            return paginationInterceptor;
        }
        
        // 最新版
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
            return interceptor;
        }
        
    }
    
  2. 直接使用 page 对象就可以

        // 测试分页查询
        @Test
        public void testPage(){
            /**
             * 参数一:当前页
             * 参数二:页面大小
             */
            Page<User> page = new Page<>(2,5);
            userMapper.selectPage(page,null);
    
            page.getRecords().forEach(System.out::println);
            // 总页数
            System.out.println("总页数:" + page.getPages());
        }
    

5.6 删除记录

    // 测试删除
    @Test
    public void testDeleteById(){
        // 通过 id 删除一个
        userMapper.deleteById(1L);
        // 批量删除
        userMapper.deleteBatchIds(Arrays.asList(1,2,3));
        // 通过 map 删除
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("email",1111);
        userMapper.deleteByMap(map);
    }

5.7 逻辑删除

物理删除:从数据库中直接移除

逻辑删除:在数据库中没有被移除,而是通过一个变量来让他生效,deleted = 0 deleted = 1

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

测试:

  1. 在数据表中增加一个 deleted 字段

  2. 实体类中增加字段注解

    @TableLogic// 逻辑删除
    private Integer deleted;
    
  3. 配置组件

    在新版本中不需要加组件的注册

    • 老版本

      @Bean
      public ISqlInjector sqlInjector(){
          return new LogicSqlInjector();
      }
      
  4. 在配置文件中配置

    # 配置逻辑删除
    # 逻辑已删除值(默认为 1)
    # 逻辑未删除值(默认为 0)
    mybatis-plus.global-config.db-config.logic-delete-value=1
    mybatis-plus.global-config.db-config.logic-not-delete-value=0
    
  5. 测试

    逻辑删除执行的是 update 操作不是删除操作,数据库中还是存在该条记录,但是查询记录是查不到的

6. 乐观锁

乐观锁:总是认为不会出现问题,无论做什么都不会去上锁,如果出现了问题,再次更新值测试

悲观锁:总是认为v会出现问题,无论干什么都会上锁,再去操作

  • 乐观锁实现方式:

    • 取出记录时,获取当前 version
    • 更新时,带上这个 version
    • 执行更新时,set version = newVersion where version = old Version
    • 如果 version 不对,就更新失败
    ---A
    乐观锁:1. 先查询,获得版本号  version = 1
    update user set name = "李四", version = version + 1 
        where id = 2 and version = 1
    ---B
    线程抢先完成,这个时候 version = 2 ,会导致 A 修改失败
    update user set name = "李四", version = version + 1 
        where id = 2 and version = 1
    

测试一下 MP 的乐观锁插件

  1. 给数据库中增加 version 字段,设置默认值为 1

  2. 实体类加上对应的字段

    @Version // 乐观锁 Version 注解
    private Integer version;
    
  3. 注册组件

    // Spring Boot 方式
    @Configuration
    @MapperScan("按需修改")
    public class MybatisPlusConfig {
        /**
         * 旧版
         */
        @Bean
        public OptimisticLockerInterceptor optimisticLockerInterceptor() {
            return new OptimisticLockerInterceptor();
        }
        
        /**
         * 新版
         */
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
            mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
            return mybatisPlusInterceptor;
        }
    }
    
  4. 测试

    • 单线程情况下

          // 测试乐观锁成功
          @Test
          public void testOptimisticLocker(){
              // 1. 查询用户信息
              User user = userMapper.selectById(1L);
              // 2. 修改用户信息
              user.setName("李莉莉");
              // 3. 执行更新操作
              int i = userMapper.updateById(user);
              System.out.println(i);
          }
      

      数据库中修改 version 字段,变成 2

    • 多线程情况

      // 测试乐观锁失败,多线程下
      @Test
      public void testOptimisticLocker2(){
          // 线程 1
          User user = userMapper.selectById(1L);
          user.setName("李莉莉11");
      
          // 模拟另一个线程执行了插队操作
          User user2 = userMapper.selectById(1L);
          user2.setName("李莉莉11");
          userMapper.updateById(user2);
      		// 这里可以使用 自旋锁来尝试多次提交·
          userMapper.updateById(user);// 如果没有乐观锁就会覆盖插队线程的值
      }
      

7. 性能分析插件

我们在平时的开发中,会遇到一些慢 sql,可以通过测试、druid 来操作

MybatisPlus 也提供性能分析插件,如果超过这个时间停止运行

3.3.1 版本以上的 Mybatis-Plus 需要使用第三方工具(p6spy)来实现sql语句的分析

  1. 导入依赖

            <!--MybatisPlus sql执行性能分析-->
            <dependency>
                <groupId>p6spy</groupId>
                <artifactId>p6spy</artifactId>
                <version>3.9.1</version>
            </dependency>
    
  2. 编写配置文件

    • application.properties

    在这里需要修改连接连接数据库的驱动和地址

    spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatis_plus?			  useSSL=false&useUnicode=true&characterEnCoding=UTF-8&serverTimezone=GMT
    spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
    
    • 在 resources 文件夹下创建 spy.properties 配置文件
    #3.2.1以上使用
    modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
    #3.2.1以下使用或者不配置
    #modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
    # 自定义日志打印
    logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
    #日志输出到控制台
    appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
    # 使用日志系统记录 sql
    #appender=com.p6spy.engine.spy.appender.Slf4JLogger
    # 设置 p6spy driver 代理
    deregisterdrivers=true
    # 取消JDBC URL前缀
    useprefix=true
    # 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
    excludecategories=info,debug,result,commit,resultset
    # 日期格式
    dateformat=yyyy-MM-dd HH:mm:ss
    # 实际驱动可多个
    #driverlist=org.h2.Driver
    # 是否开启慢SQL记录
    outagedetection=true
    # 慢SQL记录标准 2 秒
    outagedetectioninterval=2
    
  3. 测试运行

    执行查询命令,执行时间是 14ms

8. 条件构造器

非常重要:Wrapper,我们可以写一些复杂的 sql 就可以使用它来代替

直接使用即可

    // 查询name不为空的用户,并且邮箱不为空的用
    @Test
    public void test1(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("id")
                .isNotNull("email");
        userMapper.selectList(wrapper).forEach(System.out::println);
    }
    // 查询姓名是 Tom 的记录
    @Test
    public void test2(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name","Tom");
        User user = userMapper.selectOne(wrapper);
        System.out.println(user);
    }
    // 查询年龄在 19 到 25 之间的
    @Test
    public void test3(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("age", 19, 25);
        userMapper.selectList(wrapper).forEach(System.out::println);
    }

    // 模糊查询
    @Test
    public void test4(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.notLike("name","o")
                .likeRight("email","t");
        userMapper.selectList(wrapper).forEach(System.out::println);
    }

    // 子查询
    @Test
    public void test5(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.inSql("id","select id from user where id > 2");
        List<Object> objects = userMapper.selectObjs(wrapper);
        objects.forEach(System.out::println);
    }
    // 排序查询
    @Test
    public void test6(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        userMapper.selectList(wrapper).forEach(System.out::println);
    }

9. 代码生成器

  1. 导入依赖

            <!--导入 mybatis-plus 依赖-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.3.1.tmp</version>
            </dependency>
    
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>3.4.1</version>
            </dependency>
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-engine-core</artifactId>
                <version> 2.3</version>
            </dependency>
    
  2. 创建自动创建的类文件

    package com.example;
    
    import com.baomidou.mybatisplus.annotation.DbType;
    import com.baomidou.mybatisplus.annotation.FieldFill;
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.generator.AutoGenerator;
    import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
    import com.baomidou.mybatisplus.generator.config.GlobalConfig;
    import com.baomidou.mybatisplus.generator.config.PackageConfig;
    import com.baomidou.mybatisplus.generator.config.StrategyConfig;
    import com.baomidou.mybatisplus.generator.config.po.TableFill;
    import com.baomidou.mybatisplus.generator.config.rules.DateType;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    
    import java.util.ArrayList;
    
    // 代码自动生成
    public class AutoCode {
        public static void main(String[] args) {
            // 需要构建一个代码生成器
            AutoGenerator mpg = new AutoGenerator();
            // 配置策略
            /// 1. 全局配置
            GlobalConfig gc = new GlobalConfig();
            // 获取用户目录
            String projectPath = System.getProperty("user.dir");
            gc.setOutputDir(projectPath + "/src/main/java");
            // 设置作者
            gc.setAuthor("lishisen");
            // 设置是否打开资源管理器
            gc.setOpen(false);
            gc.setFileOverride(false);//是否覆盖
            gc.setServiceName("%sService"); // 去 Service 的 I 前缀
            gc.setIdType(IdType.ASSIGN_ID);// 设置主键策略
            gc.setDateType(DateType.ONLY_DATE);//设置日期类型
            gc.setSwagger2(true);// 设置是否配置 swagger
            mpg.setGlobalConfig(gc);
    
            // 2. 设置数据源
            DataSourceConfig dataSourceConfig = new DataSourceConfig();
            dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEnCoding=UTF-8&serverTimezone=GMT");
            dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
            dataSourceConfig.setUsername("root");
            dataSourceConfig.setPassword("root");
            dataSourceConfig.setDbType(DbType.MYSQL);
            mpg.setDataSource(dataSourceConfig);
            // 3. 包的配置
            PackageConfig packageConfig = new PackageConfig();
            packageConfig.setModuleName("blog");
            packageConfig.setParent("com.miss");
            packageConfig.setEntity("pojo");
            packageConfig.setMapper("mapper");
            packageConfig.setService("service");
            packageConfig.setController("controller");
            mpg.setPackageInfo(packageConfig);
            // 4. 策略配置
            StrategyConfig strategy = new StrategyConfig();
            strategy.setInclude("user");// 设置要映射的表名,重要,可以写多个
            strategy.setNaming(NamingStrategy.underline_to_camel);// 设置包的命名规则,下划线转驼峰命名
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);// 列名,下划线转驼峰命名
            strategy.setEntityLombokModel(true);// 自动生成 lombok
            strategy.setLogicDeleteFieldName("deleted"); // 逻辑删除
            // 自动填充配置
            TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
            TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
            ArrayList<TableFill> tableFills = new ArrayList<>();
            tableFills.add(createTime);
            tableFills.add(updateTime);
            strategy.setTableFillList(tableFills);
            // 乐观锁
            strategy.setVersionFieldName("version");
            // 开启 Restful 的驼峰命名
            strategy.setRestControllerStyle(true);
            strategy.setControllerMappingHyphenStyle(true);//localhost:8080//hello_id_2
            mpg.setStrategy(strategy);
            // 执行
            mpg.execute();
        }
    }
    
  3. 测试

学习参考视频网址