MyBatisPlus乐观锁插件

当要更新一条记录的时候,希望这条记录没有被别人更新,如果已经更新,则此时更新失败。

  • 乐观锁实现方式
    1)取出记录时,获取当前 version;
    2)更新时,带上这个 version;
    3)执行更新时, set version = newVersion where version = oldVersion,如果 version 不对,就更新失败;

配置方式

乐观锁配置需要两步:

1.配置插件
@Configuration
@MapperScan("com.giser.mybatisplus.mapper")
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 添加乐观锁插件
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }

}
2.在实体类的字段上加上@Version注解
@Data
public class Product {
    private Long id;
    private String name;
    private Integer price;

    @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 不能复用!!!

测试

@SpringBootTest
public class ConcurrentUpdateTest {

    @Autowired
    private ProductMapper productMapper;

    @Test
    public void testConcurrentUpdate() {
        //小李取数据
        Product p1 = productMapper.selectById(1L);
        //小王取数据
        Product p2 = productMapper.selectById(1L);
        //小李修改 + 50
        p1.setPrice(p1.getPrice() + 50);
        int result1 = productMapper.updateById(p1);
        System.out.println("小李修改的结果:" + result1);
        //小王修改 - 30
        p2.setPrice(p2.getPrice() - 30);
        int result2 = productMapper.updateById(p2);
        System.out.println("小王修改的结果:" + result2);
        if(result2 == 0){
            //失败重试,重新获取version并更新
            p2 = productMapper.selectById(1L);
            p2.setPrice(p2.getPrice() - 30);
            result2 = productMapper.updateById(p2);
        }
        System.out.println("小王修改重试的结果:" + result2);
        //老板看价格
        Product p3 = productMapper.selectById(1L);
        System.out.println("老板看价格:" + p3.getPrice());
    }

}
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值