mybatis-plus如何使用乐观锁

什么是乐观锁:
就是我们每一次操作数据后,我们就会更改他的版本号,当另外的线程若想要对该数据进行操作,检查版本号是否与自己获得的版本号一致,如果不一致,那么我们就会取消该操作。

在mybatis-plus中,我们使用注解@Version标注我们表类的一个属性,使之成为我们的版本号。我们每一次对该表操作就会令他自增1.

例子:
①、注解我们的版本号

@Data
@TableName("t_product")
public class Product {
    private Long id;
    private String name;
    private Integer price;
//    表示这个为版本号
    @Version
    private Integer version;
}

②、添加我们的乐观锁拦截器


@MapperScan("com.atguigu.mybatisplus.mapper")
@Configuration
public class mybatisConfig {

    @Bean
    public MybatisPlusInterceptor MPI(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
//        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        return mybatisPlusInterceptor;
    }

}

③、测试:

@SpringBootTest
public class postiveLockTest {

    @Autowired
    productMapper productMapper;

//    @Transactional
    @Test
    public void test(){
//他们查询的价格:
        Product WangProduct = productMapper.selectById(1);
        System.out.println("小王查询的价格:" + WangProduct.getPrice());

        Product LiProduct = productMapper.selectById(1);
        System.out.println("小李查询的价格:" + LiProduct.getPrice());

//小王将价格上升50
        WangProduct.setPrice(WangProduct.getPrice()+50);
        productMapper.updateById(WangProduct);
//小李将价格下降30
        LiProduct.setPrice(LiProduct.getPrice()-30);
//        此时修改会不成功,因为小李获得的版本号与目前库里的版本号不同,所以我们就无法进行修改
        int Updateresult = productMapper.updateById(LiProduct);
        System.out.println("是否可以修改:" + Updateresult);


//        改良:判断是否斯修改成功,不成功再次获得进行修改
        if (Updateresult == 0){
            Product Newproduct = productMapper.selectById(1);
            Newproduct.setPrice(Newproduct.getPrice() -30);
            System.out.println("新的价格"+ Newproduct.getPrice());

            productMapper.updateById(Newproduct);

        }

        Product Bossproduct = productMapper.selectById(1);
        System.out.println("boss查询的价格为:"+Bossproduct.getPrice());

    }


}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值