当前位置:   article > 正文

mybatis-plus自带的乐观锁_mybatisplus 乐观锁

mybatisplus 乐观锁


mysbatis-plus乐观锁原理:
mysbatis-plus进行修改操作时,会将数据库中version字段的值拿出来和上一个查询时的得到的version值做对比,如果两个值相同则执行修改操作。若不相同,不执行修改操作。

1.场景

	阎王看孙悟空能活500岁很不爽,让判官甲给孙悟空削去400岁。
	过了一会阎王感觉削多了,让判官乙再去给加上孙悟空加上300岁,只削孙悟空100岁就行了。 
	没想到判官甲偷懒了,和判官乙近乎同时操纵的生死簿。
	这样甲拿出来是500岁,乙拿出来也是500岁。
	甲拿的500岁减去400岁变为100岁存入数据库,乙拿的500岁加上300岁变为800岁存入生死簿。
	没错判官甲的操作被覆盖了,孙悟空变成800岁了。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

1.1.模拟冲突

代码,建立测试文件

	@Test
    void OptimisticLock(){
        Students student1 = studentsMapper.selectById(1);
        System.out.println("孙悟空的年龄 甲:" + student1.getAge());

        Students student2 = studentsMapper.selectById(1);
        System.out.println("孙悟空的年龄 乙:" + student2.getAge());

        student1.setAge(student1.getAge()-400);
        int result = studentsMapper.updateById(student1);
        System.out.println("甲是否更改年龄 : " + student1.getAge());

        student2.setAge(student2.getAge()+300);
        int result2 = studentsMapper.updateById(student2);
        System.out.println("乙是否更改年龄 : " + student2.getAge());
        
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

运行结果:,,,,这里可以看到孙悟空的年龄变为了800岁,与阎王400岁的要求不符。
在这里插入图片描述

2.添加乐观锁

2.1数据库添加字段

在这里插入图片描述

2.2配置文件中增加乐观锁拦截器

@Configuration
public class MpConfig {
    @Bean
    public MybatisPlusInterceptor MybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //配置mybatisplus分页拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        //添加乐观锁拦截器
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

2.3类的属性上添加注解

在这里插入图片描述

2.4再次运行测试文件

说明乙修改数据库的操作并没有进行。
在这里插入图片描述

测试结果变为了100,也说明判官乙的操作并没有并没有进行。
在这里插入图片描述

3.优化流程

将乙更改年龄的代码修改为

   student2.setAge(student2.getAge()+300);
        int result2 = studentsMapper.updateById(student2);
        System.out.println("乙是否更改年龄 : " + result2);
        if (result2 == 0){
            Students student3 = studentsMapper.selectById(student2);
            student3.setAge(student3.getAge()+300);
            int result3 = studentsMapper.updateById(student3);
            System.out.println("乙是否更改年龄 : " + result3);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

运行结果:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/435902
推荐阅读
相关标签
  

闽ICP备14008679号