1. 简单使用步骤
配置数据库连接和日志
# 配置数据库连接
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?userSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
在主程序上配置包的扫描
@MapperScan ( "cn.zh.mapper" )
写mapper类
@Repository
public interface UserMapper extends BaseMapper < User > {
}
测试查询所有
@Autowired
private UserMapper userMapper;
@Test
void contextLoads ( ) {
List < User > users = userMapper. selectList ( null ) ;
}
2. 自动填充操作
数据库级别的:在数据库的表中添加create_time和update_time两列
代码级别的
@TableField ( fill = FieldFill . INSERT)
private Date createTime;
@TableField ( fill = FieldFill . INSERT_UPDATE)
private Date updateTime;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill ( MetaObject metaObject) {
this . setFieldValByName ( "createTime" , new Date ( ) , metaObject) ;
this . setFieldValByName ( "updateTime" , new Date ( ) , metaObject) ;
}
@Override
public void updateFill ( MetaObject metaObject) {
this . setFieldValByName ( "updateTime" , new Date ( ) , metaObject) ;
}
}
3. 乐观锁和悲观锁
乐观锁:它总是认为不会出现问题,无论干什么都不会上锁!如果出现了问题,再次更新值测试 乐观锁实现方式: 1. 取出记录时,获取当前version 2. 更新时,带上这个version 3. 执行更新时,set version = new Version where version = oldVersion 4. 如果version不对,就更新失败
@Version
private Integer version;
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor ( ) {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor ( ) ;
mybatisPlusInterceptor. addInnerInterceptor ( new OptimisticLockerInnerInterceptor ( ) ) ;
return mybatisPlusInterceptor;
}
悲观锁:它总是认为总是出现什么问题,无论干什么都会上锁!再去操作!
4. 查询操作
分页查询
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor2 ( ) {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor ( ) ;
interceptor. addInnerInterceptor ( new PaginationInnerInterceptor ( DbType . H2) ) ;
return interceptor;
}
Page < User > page = new Page < > ( 1 , 2 ) ;
Page < User > pageUser = userMapper. selectPage ( page, null ) ;
pageUser. getRecords ( ) . forEach ( System . out:: println ) ;
wrapper查询器查询
QueryWrapper < User > wrapper = new QueryWrapper < > ( ) ;
wrapper. isNotNull ( "name" )
. isNotNull ( "email" )
. ge ( "age" , 12 ) ;
userMapper. selectList ( wrapper) . forEach ( System . out:: println ) ;
5. 逻辑删除
物理删除:在数据库中直接移除
逻辑删除:在数据库中没有被移除,而是通过一个变量让他失效!deleted=0 ==> deleted=1
在数据库中加入deleted字段 实体类中加入deleted字段
@TableLogic
private Integer deleted;
# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-field=deleted
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0