MyBatisPlus乐观锁

主要适用场景

意图:

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

乐观锁实现方式:

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

1,数据库添加字段

2,实体类加入注解

特别说明:

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

3,注册组件

package com.zl.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlus {
    
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

}

4,测试

void update(){

        //第一个人来更新数据
        TUser tUser = tUserMapper.selectById(1280317621462495233L);
        tUser.setUsername("zl222");
        tUser.setPassword("222");

        //第二个人来插队
        TUser tUser2 = tUserMapper.selectById(1280317621462495233L);
        tUser2.setUsername("zl555");
        tUser2.setPassword("555");
        tUserMapper.updateById(tUser2);
        
        
        tUserMapper.updateById(tUser);
        
    }

谁先完成了更新操作算谁成功,完成的过程就是CAS

版本号version也解决了ABA问题

原文地址:https://www.cnblogs.com/zhulei2/p/13259279.html