• MyBatis-Plus


    1.什么是MyBatis-Plus

    MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
    mybatis plus 官网
    建议安装 MybatisX 插件

    2.整合MyBatis-Plus

            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.4.1</version>
            </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    自动配置
    ● MybatisPlusAutoConfiguration 配置类,MybatisPlusProperties 配置项绑定。mybatis-plus:xxx 就是对mybatis-plus的定制
    ● SqlSessionFactory 自动配置好。底层是容器中默认的数据源
    ● mapperLocations 自动配置好的。有默认值。classpath*:/mapper/**/*.xml;任意包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件。 建议以后sql映射文件,放在 mapper下
    ● 容器中也自动配置好了 SqlSessionTemplate
    ● @Mapper 标注的接口也会被自动扫描;建议直接 @MapperScan(“com.atguigu.admin.mapper”) 批量扫描就行

    优点:
    ● 只需要我们的Mapper继承 BaseMapper 就可以拥有crud能力

    Mybatis-plus总结

    mybatis - plus 官网 https://baomidou.com/

    在这里插入图片描述

    1、简单的查询

    • 1、现在mapper接口上继承BaseMapper
    @Mapper
    public interface EmployeeMapper extends BaseMapper<Employee> {
    }
    
    • 1
    • 2
    • 3
    • 2、service接口继承IService
    public interface EmployeeService extends IService<Employee> {
    }
    
    • 1
    • 2
    • 3、service实现类继承ServiceImpl 实现 EmployeeService
    @Service
    public class EmployeeServiceImpl
            extends ServiceImpl<EmployeeMapper,Employee>
            implements EmployeeService{
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 4、LambdaQueryWrapper 和QueryWrapper的区别

    QueryWrapper 的列名匹配使用的是 “数据库中的字段名(一般是下划线规则)”
    LambdaQueryWrapper 的列名匹配使用的是“Lambda的语法,偏向于对象”

    		// 1.1 创建一个条件构造器
            LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
            // 添加条件
            queryWrapper.eq(Employee::getUsername,employee.getUsername());
            // 再使用mybatis-plus自带的方法查询返回结果
            Employee emp = employeeService.getOne(queryWrapper);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2、分页查询

    1、使用Page对象一定要添加配置类

    @Configuration
    public class MybatisPlusConfig {
    
        /**
         * 分页配置
         * @return
         */
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor(){
            MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
            mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
            return mybatisPlusInterceptor;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2、分页构造器

    Page<Employee> pageInfo = new Page<>(page,pageSize);
    
    • 1

    3、添加构造器

    @param1:是否有字符串传入,当有的时候再调用函数

    @param2:数据库对应的字段

    @param3:传入的数据

    queryWrapper.like(boolean condition, R column, Object val)

    // 构造条件构造器
    LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
    // 判断name不为kong ,并且排序
    queryWrapper.like(StringUtils.hasText(name),Employee::getName,name)
            .orderByDesc(Employee::getUpdateTime);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4、执行

    继承IService接口并且实现自带page方法返回一个page对象

    employeeService.page(pageInfo,queryWrapper);
    
    • 1

    page对象封装了一些属性

    在这里插入图片描述

    3、查询单条数据

    根据id查询

    LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Employee::getId,id);
    Employee employee = employeeService.getOne(queryWrapper);
    return R.success(employee);
    
    • 1
    • 2
    • 3
    • 4

    也可以

    employeeService.getById(id);
    
    • 1

    反正mybatis-plus封装了很多方法,想用啥就用啥!

    4、自动填充

    官网案例:

    @Slf4j
    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
    
        @Override
        public void insertFill(MetaObject metaObject) {
            log.info("start insert fill ....");
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
            // 或者
            this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
            // 或者
            this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)
        }
    
        @Override
        public void updateFill(MetaObject metaObject) {
            log.info("start update fill ....");
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐)
            // 或者
            this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
            // 或者
            this.fillStrategy(metaObject, "updateTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 注解填充字段 @TableField(.. fill = FieldFill.INSERT) 生成器策略部分也可以配置!

    注意事项:

    • 填充原理是直接给entity的属性设置值!!!
    • 注解则是指定该属性在对应情况下必有值,如果无值则入库会是null
    • MetaObjectHandler提供的默认方法的策略均为:如果属性有值则不覆盖,如果填充值为null则不填充
    • 字段必须声明TableField注解,属性fill选择对应策略,该声明告知Mybatis-Plus需要预留注入SQL字段
    • 填充处理器MyMetaObjectHandler在 Spring Boot 中需要声明@Component@Bean注入
    • 要想根据注解FieldFill.xxx字段名以及字段类型来区分必须使用父类的strictInsertFill或者strictUpdateFill方法
    • 不需要根据任何来区分可以使用父类的fillStrategy方法
    • update(T t,Wrapper updateWrapper)时t不能为空,否则自动填充失效
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;
    
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
    
    @TableField(fill = FieldFill.INSERT)
    private Long createUser;
    
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Long updateUser;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 自定义实现类 MyMetaObjectHandler

      package com.sky.reggie.common;
      
      import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
      import lombok.extern.slf4j.Slf4j;
      import org.apache.ibatis.reflection.MetaObject;
      import org.springframework.context.annotation.Configuration;
      
      import java.time.LocalDateTime;
      
      /**
       * @author 尹稳健~
       * @version 1.0
       * 自动填充类
       */
      
      @Configuration
      @Slf4j
      public class MyMetaObjectHandler implements MetaObjectHandler {
      
          @Override
          public void insertFill(MetaObject metaObject) {
              log.info("=======自动填充insert=======");
              log.info(metaObject.toString());
      
              this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
              this.strictInsertFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
              this.strictInsertFill(metaObject,"createUser", Long.class,BaseContext.getCurrentId());
              this.strictInsertFill(metaObject,"updateUser", Long.class,BaseContext.getCurrentId());
          }
      
          @Override
          public void updateFill(MetaObject metaObject) {
              log.info("=======自动填充update=======");
              long id = Thread.currentThread().getId();
              log.info("当前线程的id:{}",id);
              metaObject.setValue("updateTime",LocalDateTime.now());
              metaObject.setValue("updateUser",BaseContext.getCurrentId());
              log.info(metaObject.toString());
          }
      }
      
      • 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

    5、

  • 相关阅读:
    html转pdf(总结五种方法Java)
    IO口电路种类
    本地PHP搭建简单Imagewheel私人云图床,在外远程访问——“cpolar内网穿透”
    【NOWCODER】- Python:类型转换
    rk3568 LCD dtsi文件配置选项含义说明
    SQL Server远程登录失败
    如何修炼成“神医”——《OceanBase诊断系列》之一
    配置neo4j bolt+s ssl
    华为HCIE云计算之IPsan存储裸设备映射给Linux主机
    浅谈mysql 第一篇
  • 原文地址:https://blog.csdn.net/weixin_46073538/article/details/123635048