主键生成策略 @TabelID
uuid
自增ID
雪花算法
mybatis-plus 的主键策略
package com.baomidou.mybatisplus.annotation;
public enum IdType {
AUTO(0), //数据库自增ID 记住表ID字段一定是自增的
NONE(1), //未设置
INPUT(2), //手动输入
ID_WORKER(3), //默认的
UUID(4), // uuid
ID_WORKER_STR(5);
private int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
更新操作
//测试更新
@Test
void update() {
User user = new User();
user.setName("tianqi");
user.setAge(22);
user.setEmail("17610373883@163.com");
user.setId(1383375464730480641L);
int i = userMapper.updateById(user);
System.out.println(i);
System.out.println(user);
}
自动填充@TableField
这里用的版本是3.0.5 新版本可能不太一样 自行去官网查询
注解填充字段 @TableField(.. fill = FieldFill.INSERT)
生成器策略部分也可以配置!
public class User {
// 注意!这里需要标记为填充字段
@TableField(.. fill = FieldFill.INSERT)
private String fillField;
}
实现元对象处理器接口:com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
@Component // 加入spring容器中,不然不会生效
public class ImmortalMetaObjectHandler 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);
}
}
执行测试
@Test
void insert() {
User user = new User();
user.setName("tianqi");
user.setAge(22);
user.setEmail("2211738262@163.com");
int insert = userMapper.insert(user); //自动生成id
System.out.println(insert);
System.out.println(user);
}
结果
乐观锁 @Version
乐观锁实现机制: @Version
- 取出记录是带上version
- 更新时,带上这个version
- 执行更新时,set version = newversion where version = oldVersion
- 如果不对则更新失败
update user set name = "tianqi", version = version+1 where id = #{id} and version = 1
注册组件
@Configuration
public class MybatisPlusConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
测试
//optimisticLocker
@Test
void optimisticLocker() {
User user = userMapper.selectById(1);
System.out.println("user : " + user);
user.setName("dutianqi");
int i = userMapper.updateById(user);
System.out.println("成功的条数:" + i);
}
模拟多线程下失败的案例
//localdatetime 模拟多线程下失败的案例
@Test
void optimisticLocker2() {
User user = userMapper.selectById(1);
user.setName("dutianqi");
//模拟线程插队
User user2 = userMapper.selectById(1);
user2.setName("lv");
//先执行第二个线程的sql
userMapper.updateById(user2);
//这里会失败,通过自旋锁重复提交
userMapper.updateById(user);
}
查询多种操作
//批量查询 一个集合
@Test
void selectBatchIds() {
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
//按条件查询 map
@Test
void selectByMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("id",1);
map.put("name","lv");
map.put("age",18);
userMapper.selectByMap(map);
}
分页查询
注册组件
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
测试查询
//按分页查询
@Test
void selectByLimit() {
IPage<User> userIPage = userMapper.selectPage(new Page<>(1, 5), null);
List<User> records = userIPage.getRecords(); //获取查询的数据
records.forEach(System.out::println);
System.out.println(userIPage.getCurrent()); //现在的页数
System.out.println(userIPage.getPages()); //一共有几页
System.out.println(userIPage.getSize()); //现在page的大小
System.out.println(userIPage.getTotal()); //一共有多少条数据
}
删除
//删除
@Test
void deleteById() {
userMapper.deleteById(1383412761811251202L);
}
逻辑删除 @TableLogic
实体类 User
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@TableId(type = IdType.ID_WORKER) //主键是生成策略
private Long id;
private String name;
private Integer age;
private String email;
@TableLogic //逻辑删除
private Integer deleted;
@Version //乐观锁注解
private Integer version;
@TableField(fill = FieldFill.INSERT) //插入时候更新
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) //更新或插入时候更新
private Date updateTime;
}
配置
// mybatis-plus 配置文件
@Configuration
public class MybatisPlusConfig {
//逻辑删除插件
@Bean
public ISqlInjector iSqlInjector(){
return new LogicSqlInjector();
}
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
//乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
yaml 文件
#配置控制台日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#配置逻辑删除
global-config:
logic-delete-field: deleted # 全局逻辑删除的实体字段名
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0
测试
//逻辑删除
@Test
void fakeDeleteById() {
userMapper.deleteById(5L);
}
//这里时更新语句 将伪删除的字段改成了1
性能分析插件
配置
@Bean
@Profile({"dev"})
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
//设置sql最大执行时间 毫秒单位 超过这个时间则不执行
// performanceInterceptor.setMaxTime(1);
//设置sql格式化
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
测试
sql 变得更好看了 还有执行的时间
Wrapper
https://mp.baomidou.com/guide/wrapper.html
用于查询复杂的sql
//wrapper
@Test
void wrapper() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
//查新name 和邮箱不为空 并且年龄大于等于12岁
wrapper.isNotNull("name")
.isNotNull("email")
.ge("age",12);
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
test
//wrapper selectOne
@Test
void wrapper1() {
User user = userMapper.selectOne(new QueryWrapper<User>().eq("name", "lv"));
System.out.println(user);
}
//wrapper 区间
@Test
void wrapper2() {
Integer count = userMapper.selectCount(new QueryWrapper<User>().between("age", 12, 30));
System.out.println(count);
}
模糊查询
//wrapper 模糊查询
@Test
void wrapper3() {
List<User> users = userMapper.selectList(new QueryWrapper<User>()
.notLike("name", "l")
.like("email", "4")
.likeRight("name", "S")
);
users.forEach(System.out::println);
}
insql
//wrapper insql
@Test
void insql() {
QueryWrapper<User> wrapper = new QueryWrapper<User>().inSql("id", "select id from user");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
排序
//wrapper desc asc
@Test
void descAsc() {
QueryWrapper<User> wrapper = new QueryWrapper<User>().orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}