一、引言
乐观锁 : 很乐观,对任何事情都保持着一个乐观的态度,认为别人不会修改数据,所以不会上锁,只是在更新数据的时候,去判断这条数据有没有被别人修改过。
悲观锁:很悲观,总是假设最坏的情况,每次去拿数据的时候都认为别人会修改数据,所以在每次拿数据的时候都会上锁。
如果说大量读取数据操作的时候,适合使用乐观锁。如果冲突较多建议使用悲观锁。
二、实现
步骤一 :springboot 方式 ,配置乐观锁插件
package com.qianting.demo.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author WangYan
* @date 2021/10/14 10:16
* MybatisPlus 配置类
*/
@Configuration
public class MybatisPlusConfig {
/**
* 乐观锁插件
* @return
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
步骤二:实体类定义 version 字段加上 @vesion 注解
步骤三 : 测试
/**
* 乐观锁
*/
@Test
public void Test1(){
Offer offer = new Offer();
offer.setId(1);
offer.setSal("8000");
// 需要把之前从数据库读出来的版本号设置进去
offer.setVersion(2);
int i = offerMapper.updateById(offer);
System.out.println(i);
}