MyBatisPlus(七)乐观锁

本文涉及的产品
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
日志服务 SLS,月写入数据量 50GB 1个月
简介: 使用乐观锁的意图是:当要更新一条记录的时候,希望这条记录没有被别人更新。那么需要在表中增加一个字段version来实现。

使用乐观锁的意图是:当要更新一条记录的时候,希望这条记录没有被别人更新。那么需要在表中增加一个字段version来实现。

乐观锁实现方式:

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

而MyBatisPlus已经封装好了乐观锁的实现,我们来配置使用即可

乐观锁配置

配置乐观锁需要2步:

  1. mybatisPlusInterceptor()配置中,增加一行乐观锁插件配置即可:interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
   
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 分页插件
    interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // 乐观锁插件
    return interceptor;
}
  1. 在实体类version字段中增加注解@Version
@Version
private Integer version;

测试代码

我们来试一下,将部门根据ID查询出来,修改其名称,并根据ID进行更新操作

@Test
public void testUpdateById() {
   
    Dept dept = deptMapper.selectById("4b0e878b5bfc2f22f44f1a3691403116");
    dept.setName("Lilei");
    int result = deptMapper.updateById(dept);
    System.out.println(result);
}

执行日志:

JDBC Connection [HikariProxyConnection@233271858 wrapping com.mysql.cj.jdbc.ConnectionImpl@62628e78] will not be managed by Spring
==>  Preparing: SELECT id,name,deleted,version,create_time,update_time FROM dept WHERE id=? AND deleted=0
==> Parameters: 4b0e878b5bfc2f22f44f1a3691403116(String)
<==    Columns: id, name, deleted, version, create_time, update_time
<==        Row: 4b0e878b5bfc2f22f44f1a3691403116, Lilei, 0, 6, null, null
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@511505e7]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@743c6ce4] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@532297836 wrapping com.mysql.cj.jdbc.ConnectionImpl@62628e78] will not be managed by Spring
==>  Preparing: UPDATE dept SET name=?, version=? WHERE id=? AND version=? AND deleted=0
==> Parameters: Lilei(String), 7(Integer), 4b0e878b5bfc2f22f44f1a3691403116(String), 6(Integer)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@743c6ce4]
1

从执行日志中可以看出会增加 set version = newVersion where version = oldVersion,表示乐观锁成功使用。为了进一步验证,我们模拟一个错误的执行

    @Test
    public void testUpdateById2() {
   
        Dept dept1 = deptMapper.selectById("4b0e878b5bfc2f22f44f1a3691403116");
        dept1.setName("Lilei1");

        Dept dept2 = deptMapper.selectById("4b0e878b5bfc2f22f44f1a3691403116");
        dept2.setName("Lilei2");

        int result = deptMapper.updateById(dept1);
        System.out.println(result);

        int result2 = deptMapper.updateById(dept2);
        System.out.println(result2);
    }

执行日志:

JDBC Connection [HikariProxyConnection@1491623023 wrapping com.mysql.cj.jdbc.ConnectionImpl@a137d7a] will not be managed by Spring
==>  Preparing: SELECT id,name,deleted,version,create_time,update_time FROM dept WHERE id=? AND deleted=0
==> Parameters: 4b0e878b5bfc2f22f44f1a3691403116(String)
<==    Columns: id, name, deleted, version, create_time, update_time
<==        Row: 4b0e878b5bfc2f22f44f1a3691403116, Lilei, 0, 7, null, null
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2a389173]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3bbf9027] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@281151050 wrapping com.mysql.cj.jdbc.ConnectionImpl@a137d7a] will not be managed by Spring
==>  Preparing: SELECT id,name,deleted,version,create_time,update_time FROM dept WHERE id=? AND deleted=0
==> Parameters: 4b0e878b5bfc2f22f44f1a3691403116(String)
<==    Columns: id, name, deleted, version, create_time, update_time
<==        Row: 4b0e878b5bfc2f22f44f1a3691403116, Lilei, 0, 7, null, null
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3bbf9027]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@108d55c4] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@404152906 wrapping com.mysql.cj.jdbc.ConnectionImpl@a137d7a] will not be managed by Spring
==>  Preparing: UPDATE dept SET name=?, version=? WHERE id=? AND version=? AND deleted=0
==> Parameters: Lilei1(String), 8(Integer), 4b0e878b5bfc2f22f44f1a3691403116(String), 7(Integer)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@108d55c4]
1
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7ee3d262] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@60221145 wrapping com.mysql.cj.jdbc.ConnectionImpl@a137d7a] will not be managed by Spring
==>  Preparing: UPDATE dept SET name=?, version=? WHERE id=? AND version=? AND deleted=0
==> Parameters: Lilei2(String), 8(Integer), 4b0e878b5bfc2f22f44f1a3691403116(String), 7(Integer)
<==    Updates: 0
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7ee3d262]
0

从日志中我们可以看出,第一个update语句执行了,而第二个没有执行,验证成功。

特别说明

乐观锁特别说明:

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

上一篇:SpringBoot 全家桶 | MyBatisPlus(六)软删除(逻辑删除)
下一篇:SpringBoot 全家桶 | MyBatisPlus(八)自动填充字段(createTime/updateTime)

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
12天前
|
XML 前端开发 Java
Mybatis-Plus乐观锁配置
Mybatis-Plus乐观锁配置
15 1
|
2月前
|
SQL 数据库
MyBatisPlus之逻辑删除、MyBatisPlus解决并发问题的乐观锁机制
MyBatisPlus之逻辑删除、MyBatisPlus解决并发问题的乐观锁机制
36 2
|
2月前
|
SQL 存储 算法
Mybatis-Plus- CRUD接口-主键策略-自动填充和乐观锁-分页-逻辑删除-条件构造器和常用接口
Mybatis-Plus- CRUD接口-主键策略-自动填充和乐观锁-分页-逻辑删除-条件构造器和常用接口
|
2月前
|
数据库
MyBatisPlus-乐观锁概念及实现步骤
MyBatisPlus-乐观锁概念及实现步骤
63 0
|
2月前
|
存储 Java 数据库连接
MyBatis-Plus如何娴熟运用乐观锁
MyBatis-Plus如何娴熟运用乐观锁
103 0
|
2月前
|
Java 关系型数据库 数据库连接
干翻Mybatis源码系列之第十二篇:基于Mybatis Plugins做一个乐观锁
干翻Mybatis源码系列之第十二篇:基于Mybatis Plugins做一个乐观锁
|
7月前
|
XML Java 数据库
mybatis-plus乐观锁
mybatis-plus乐观锁
49 0
|
12月前
|
安全 Java 数据库连接
mybatis plus整合乐观锁
mybatis plus整合乐观锁
|
12月前
|
数据库
MyBatisPlus的乐观锁和悲观锁
MyBatisPlus的乐观锁和悲观锁
118 0
|
数据库
springboot+mybatis实现乐观锁
springboot+mybatis实现乐观锁
125 0