MyBatis-Plus乐观锁插件
- 发布
- 阅读
- 5 分钟 · 1,430 字
- 状态
- 首次发布
乐观锁的实现原理
乐观锁的实现通常包括以下步骤:
读取记录时,获取当前的版本号(version)。
在更新记录时,将这个版本号一同传递。
执行更新操作时,设置
version = newVersion的条件为version = oldVersion。如果版本号不匹配,则更新失败
配置乐观锁插件
1. 配置插件
Spring XML 方式
<bean id="optimisticLockerInnerInterceptor" class="com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor"/>
<bean id="mybatisPlusInterceptor" class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
<property name="interceptors">
<list>
<ref bean="optimisticLockerInnerInterceptor"/>
</list>
</property>
</bean>Spring Boot 注解方式
@Configuration
@MapperScan("按需修改")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}2. 在实体类字段上添加 @Version 注解
import com.baomidou.mybatisplus.annotation.Version;
public class YourEntity {
@Version
private Integer version;
// 其他字段...
}注意事项
支持的 数据类型包括:int, Integer, long, Long, Date, Timestamp, LocalDateTime。
对于整数类型,newVersion 是 oldVersion + 1。
newVersion 会自动回写到实体对象中。
支持内置的 updateById(entity) 和 update(entity, wrapper), saveOrUpdate(entity), insertOrUpdate(entity) (version >=3.5.7) 方法。
自定义方法更新时如果满足内置参数的参数条件方式也会执行乐观锁逻辑,例如自定义myUpate(entity) 这个和 updateById(entity) 是等价的,会提取参数进行乐观锁填充,但更新实现需要自行处理。
在 update(entity, wrapper) 方法中,wrapper 不能复用。
修订记录
首次发布。