栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MyBatis-Plus

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MyBatis-Plus

1.什么是MyBatis-Plus

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

2.整合MyBatis-Plus
        
            com.baomidou
            >mybatis-plus-boot-starter
            3.4.1
        

自动配置
● 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 {
}
  • 2、service接口继承IService
public interface EmployeeService extends IService {
}
  • 3、service实现类继承ServiceImpl 实现 EmployeeService
@Service
public class EmployeeServiceImpl
        extends ServiceImpl
        implements EmployeeService{
}
  • 4、LambdaQueryWrapper 和QueryWrapper的区别

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

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

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

@Configuration
public class MybatisPlusConfig {

    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}

2、分页构造器

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

3、添加构造器

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

@param2:数据库对应的字段

@param3:传入的数据

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

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

4、执行

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

employeeService.page(pageInfo,queryWrapper);

page对象封装了一些属性

3、查询单条数据

根据id查询

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

也可以

employeeService.getById(id);

反正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)
    }
}
  • 注解填充字段 @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;
  • 自定义实现类 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;
    
    
    
    @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());
        }
    }
    
5、
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/992260.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号