Mybatis-Plus 乐观锁

76 阅读1分钟

乐观锁

乐观锁:它总是认为不会出现问题,无论干什么不会去上锁。如果出现了问题,再次更新值测试

悲观锁:它总是认为总会出现问题,无论干什么都会去上锁。再去操作

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败
乐观锁:先查询,获得版本号
线程A:
update user set name="xxx",version = version+1
where id = 2 and version=1

线程B: (线程抢先完成,这时候 version=2 ,会导致 A 修改失败)
update user set name="xxx",version = version+1
where id = 2 and version=1

测试乐观锁

1.给数据库中添加version字段(默认值为 1)

2.实体类加入对应的字段

@Version  //乐观锁 version 注解
private Integer version;

3.注册组件 创建 MybatisPlusConfig.java 配置类 (放在 config 包下)

package com.jia.config;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement   // 启注解事务管理
public class MybatisPlusConfig {
    
    // 注册乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}

测试结果: