MyBatis-Plus之@Version

在SpringCloud之整合ribbon之后,想到多个服务怎么保证在数据操作过程中保证数据的一致性。

翻找到了Mybatis-plus的注解@Version,这个注解实现了数据库操作的乐观锁。

目录

  • 一、使用目的
  • 二、实现方法
  • 三、使用
    • 3.1 实体类的字段上加上@Version注解
    • 3.2 创建bean
  • 四、测试

一、使用目的

当要更新一条记录的时候,希望这条记录没有被别人更新

二、实现方法

  • 取出记录时,获取当前 version
  • 更新时,带上这个 version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果 version 不对,就更新失败

三、使用

3.1 实体类的字段上加上@Version注解

@Version
private Integer version;
  • 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下 newVersion = oldVersion + 1
  • newVersion 会回写到 entity 中
  • 仅支持 updateById(id)update(entity, wrapper) 方法
  • 在 update(entity, wrapper) 方法下, wrapper 不能复用!!!

3.2 创建bean

在Application容器创建Bean

@Bean
public MybatisPlusInterceptor myOptimisticLockerInnerInterceptor(){
     MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
     interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
     return interceptor;

 }

四、测试

MyBatis-Plus之@Version_第1张图片

你可能感兴趣的:(Mybatis,intellij-idea,java)