mybatisPlus-乐观锁
数据库中添加version字段
自定义配置类中,添加乐观锁的拦截器
package com.atguigu.config; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @MapperScan(basePackages = "com.atguigu.mapper") @Configuration public class Mpconfig { //乐观锁插件 @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ //1 创建MybatisPlusInterceptor拦截器对象 MybatisPlusInterceptor mpInterceptor=new MybatisPlusInterceptor(); //2 添加乐观锁拦截器 mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return mpInterceptor; } }
MyMetaObjectHandler类中设置添加version时的默认值
@Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("version",1,metaObject); }
实体类上verison自动添加注解
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.Version; import lombok.Data; import java.util.Date; import static com.baomidou.mybatisplus.annotation.FieldFill.*; @Data public class User { @Version @TableField(fill = INSERT) private Integer version; }
测试代码
当执行更新sql时,version版本号会自动+1
@Test public void updateUserById(){ //先查询再更新 User user = userMapper.selectById(11L); user.setName("hello"); //更新时会比对当前版本号,相同会更新版本号+1 int i = userMapper.updateById(user); System.out.println(i); }
下面场景会更新失败
携带版本号为0,此时库里面版本号为2
@Test public void updateUserById(){ User user = userMapper.selectById(11L); user.setName("hello"); user.setVersion(0); int i = userMapper.updateById(user); System.out.println(i); }