Title

mybatis-plus乐观锁

乐观锁&悲观锁

乐观锁:顾名思义十分乐观,他总是认为不会出现问题,无论干什么都不上锁!如果出现了问题,再次更新值测试

悲观锁:顾名思义十分悲观,他总是认为出现问题,无论干什么都会上锁!再去操作!

乐观锁实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时,set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败
  1. 给数据库中增加version字段

  2. 实体类加对应的字段

    @Version//乐观锁version注解
    private Integer version;
    
  3. 创建配置类注册组件

    @Configuration
    @EnableTransactionManagement
    @MapperScan("com.xxx.mapper")
    public class MyBatisPlusConfig {
    
        @Bean
        public MybatisPlusInterceptor optimisticLockerInnerInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
            return interceptor;
        }
    }
    
    

posted @ 2022-04-17 13:44  手中的小黄鸭  阅读(50)  评论(0)    收藏  举报