洛阳 网站建设,北京企迪网站建设公司,wordpress 建网站,竞价排名什么意思title乐观锁与悲观锁解决方案code测试乐观锁与悲观锁
乐观锁#xff1a;十分乐观#xff0c;总是认为不会出现问题#xff0c;无论干什么#xff0c;都不会去上锁。如果出现了问题#xff0c;就再次更新值测试。
悲观锁#xff1a;十分悲观#xff0c;认为总是出现问题…
title乐观锁与悲观锁解决方案code测试乐观锁与悲观锁
乐观锁十分乐观总是认为不会出现问题无论干什么都不会去上锁。如果出现了问题就再次更新值测试。
悲观锁十分悲观认为总是出现问题无论干什么都去上锁。再去操作。 当要更新一条记录的时候希望这条记录没有被别人更新 乐观锁实现方式 取出记录时获取当前version更新时带上这个version执行更新时 set version newVersion where version oldVersion如果version不对就更新失败 -- 多线程下 锁的处理
-- 乐观锁 1. 先查询获取版本号 version 1
-- A 线程
update user set name jack, version version 1
where id 1 and version 1-- B 线程抢先完成这个时候 更新version为 2会导致A 修改失败
update user set name jack, version version 1
where id 1 and version 1解决方案 在表中加上version字段int类型默认值0 就目前最新版本的插件是3.4.1 需要将插件添加到拦截器中。不是注入bean。 新版OptimisticLockerInnerInterceptor 在3.4.1 中块过时的 OptimisticLockerInterceptor在version字段上添加Version 解决。
code
package cn.bitqian.config;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;/*** mybatis plus配置类* author echo lovely* date 2020/11/15 09:48*/EnableTransactionManagement // 开启事务
MapperScan(cn.bitqian.mapper)
Configuration
public class MyBatisPlusConfig {// mybatis插件注册Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {// 乐观锁MybatisPlusInterceptor mybatisPlusInterceptor new MybatisPlusInterceptor();// 添加乐观锁到插件中mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return mybatisPlusInterceptor;}} 字段需要添加
测试 Testvoid testOptimisticLocker1() {User user userMapper.selectById(1327447426226786310L);// 抢先修改User user1 userMapper.selectById(1327447426226786310L);user1.setName(jjj);userMapper.updateById(user1);// 不会被修改因为由于上面的修改version变了user.setName(bitqian666);userMapper.updateById(user);}