SpringBoot 全家桶 | MyBatisPlus(七)乐观锁

使用乐观锁的意图是:当要更新一条记录的时候,希望这条记录没有被别人更新。那么需要在表中增加一个字段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)

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
乐观锁是一种并发控制机制,它假设在大多数情况下,数据不会发生冲突,因此不会对数据进行加锁操作。在乐观锁中,每次更新数据时,会先检查数据的版本号或者时间戳,如果与当前版本号或时间戳一致,则说明数据没有被其他线程修改,可以进行更新操作;如果不一致,则说明数据已经被其他线程修改,此时需要进行相应的处理,例如回滚或者重新尝试更新操作。 在Mybatis中,可以通过使用版本号实现乐观锁。具体实现方式如下[^1][^2]: 1. 在数据库表中添加一个版本号字段,通常是一个整型字段。 2. 在查询数据时,将版本号字段也查询出来。 3. 在更新数据时,将版本号字段作为更新条件,并将版本号加1。 4. 在更新操作后,判断更新的行数,如果更新的行数为0,则说明数据已经被其他线程修改,需要进行相应的处理。 以下是一个使用Mybatis-Plus实现乐观锁的示例代码: ```java // 定义实体类 public class User { private Long id; private String name; private Integer version; // 省略getter和setter方法 } // 定义Mapper接口 public interface UserMapper extends BaseMapper<User> { @Update("UPDATE user SET name = #{name}, version = version + 1 WHERE id = #{id} AND version = #{version}") int updateWithVersion(User user); } // 在业务逻辑中使用乐观锁 User user = userMapper.selectById(userId); user.setName("newName"); int rows = userMapper.updateWithVersion(user); if (rows == 0) { // 处理更新失败的情况 } ``` 在上述示例中,通过在更新语句中增加版本号的判断,实现了乐观锁的功能。如果更新失败(即更新的行数为0),则说明数据已经被其他线程修改,可以根据实际需求进行相应的处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农StayUp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值