mybatis-plus and mysql
持续更新中 。。。。。。
1. 乐观锁和悲观锁的介绍
-
悲观锁
串行: 对于一条数据,在我没有完成操作之前,其他线程不能对这条数据操作
-
乐观锁
当要更新一条记录时,希望这条记录没有被别人更新
乐观锁的实现方式:
- 取出记录时,获取当前
version
- 更新时,带上这个
version
- 执行更新时,
set version = newVersion where version = oldVersion
- 如果
version
不对,就更新失败
- 取出记录时,获取当前
2. mybatis(乐观锁)
注意:mybatis-plus的版本3.5.1
主要类: OptimisticLockerInnerInterceptor
-
配置插件:
spring.xml格式
<bean class="com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor" id="optimisticLockerInnerInterceptor"/> <bean id="mybatisPlusInterceptor" class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor"> <property name="interceptors"> <list> <ref bean="optimisticLockerInnerInterceptor"/> </list> </property> </bean>
springboot 注解方式
@Configuration
public class BeanConfig {
@Bean
public IKeyGenerator myKeyGenerator(){
return new H2KeyGenerator();
}
//插件配置
//乐观锁插件,分页插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//添加插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//乐观锁
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//分页插件
return interceptor;
}
}
-
添加字段
@Version private Integer version;
3. 分页插件
主要类 PaginationInnerInterceptor
-
配置插件
@Configuration public class BeanConfig { @Bean public IKeyGenerator myKeyGenerator(){ return new H2KeyGenerator(); } //插件配置 //乐观锁插件,分页插件 @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); //添加插件 interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//乐观锁 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//分页插件 return interceptor; } }
- 测试分页插件效果
//测试分页插件 @Test public void testPagination(){ Page<User> page = new Page<>(1, 5);//当前页,每页5条数据 userMapper.selectPage(page, null);// 将查到的所有数据存入在Page对象里面 page.getRecords().forEach(System.out::println); System.out.println("===================="); System.out.println(page.getCurrent());//当前页 System.out.println(page.getPages());//总页数 System.out.println(page.getSize());//每页显示条数 System.out.println(page.getTotal());//总条数 System.out.println(page.hasNext());//是否有下一页 System.out.println(page.hasPrevious());//是否有上一页 }
4. 代码生成器
-
添加依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.2</version> </dependency>
-
创建一个方法,方法体如下 :
package com.biienu;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Collections;
/**
* @Author: biienu
* @Date: 2022/3/19 21:13
*/
@SpringBootTest
public class AutoGenearteCode {
FastAutoGenerator.create("jdbc:mysql://localhost:3306/club?characterEncoding=UTF-8&serverTimezone=GMT%2B8","root", "aoeyue")
.globalConfig(builder -> {
builder.author("biienu") // 设置作者
.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
// .outputDir("E:\\ProcessDocuments\\项目测试\\online-education\\service\\service-edu\\src\\main\\java\\com\\biienu"); // 指定输出目录
.outputDir("E:\\ProcessDocuments\\web-front\\gradual-design\\student-orgnization-end\\src\\main\\java");
})
.packageConfig(builder -> {
builder.parent("com.biienu.studentorgnizationend") // 设置父包名
.moduleName("") // 设置父包模块名
// .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "E:\\ProcessDocuments\\项目测试\\online-education\\service\\service-edu\\src\\main\\resources\\mappers")); // 设置mapperXml生成路径
.pathInfo(Collections.singletonMap(OutputFile.mapperXml,"E:\\ProcessDocuments\\web-front\\gradual-design\\student-orgnization-end\\src\\main\\resources\\mappers"));
})
.strategyConfig(builder -> {
builder.addInclude("activity","apply_activity","apply_club","club","member","message","news","user")
.entityBuilder().serviceBuilder().formatServiceFileName("%sService"); // 将生成的 Service 类名称格式化为 %sService;
// .addTablePrefix("t_", "c_"); // 设置过滤表前缀
})
.templateEngine(new VelocityTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
5. 逻辑删除
使用说明
只对自动注入的 sql 起效:
插入: 不作限制
查找: 追加 where 条件过滤掉已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
更新: 追加 where 条件防止更新到已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
删除: 转变为 更新
例如:
- 删除:
update user set deleted=1 where id = 1 and deleted=0
- 查找:
select id,name,deleted from user where deleted=0
字段类型支持说明:
支持所有数据类型(推荐使用
Integer
,Boolean
,LocalDateTime
)如果数据库字段使用
datetime
,逻辑未删除值和已删除值支持配置为字符串null
,另一个值支持配置为函数来获取值如now()
附录:
- 逻辑删除是为了方便数据恢复和保护数据本身价值等等的一种方案,但实际就是删除。
- 如果你需要频繁查出来看就不应使用逻辑删除,而是以一个状态去表示。
使用步骤 :
-
yaml配置文件修改
mybatis-plus: global-config: db-config: logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2) logic-delete-value: 1 # 逻辑已删除值(默认为 1) logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
-
实体类字段上添加注解
@TableLogic private Integer deleted;
6. 条件构造器
主要通过QueryWrapper
类
如果想进行复杂条件查询,那么需要使用条件构造器 Wapper,涉及到如下方法
1、delete
2、selectOne
3、selectCount
4、selectList
5、selectMaps
6、selectObjs
7、update
7. 自动填充
实现步骤 :
-
创建一个类,实现
MetaObjectHandler
类, 重写两个方法,如下 :public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("gmtCreate",LocalDateTime.now(), metaObject);//gmtCreate为实体字段,不是表中字段 this.setFieldValByName("gmtModified",LocalDateTime.now(), metaObject); } @Override public void updateFill(MetaObject metaObject) { this.setFieldValByName("gmtModified", LocalDateTime.now(), metaObject); } }
-
在实体类属性上添加这个注解
@TableField
, 实现如下 :@TableField(fill = FieldFill.INSERT) private LocalDateTime gmtCreate; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime gmtModified;