在实际项目中为了避免数据的并发修改问题引起的异常情况,我们通常使用乐观锁来处理处理,在MyBatis-Plus中对这块已经有很好的支持,通过以下简单配置,即可快速支持。
配置方法
- 配置插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
- 给实体Bean添加注解
@Version
private Integer version;
注意问题
和JPA不同的是,MyBatis-Plus乐观锁出现锁冲突时并不会抛异常,需要通过update方法返回的结果自行判断是否有锁冲突
参考: https://baomidou.com/guide/interceptor-optimistic-locker.html#optimisticlockerinnerinterceptor