MyBatisPlus使用Version注解(乐观锁)

Version

  • 描述:乐观锁注解、标记 @Verison 在字段上

MybatisPlus有一个乐观锁注解,在使用的时候遇到一些问题。

乐观锁的字段在基类中,模型如下:

@Data
public class TblBase {
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;

    private Date createTime;

    @Version
    private Date lastUpdateTime;

    private String enableFlag;
}

更新代码如下:

@Test
public void update() {
    QueryWrapper<TblEmployee> queryWrapper = new QueryWrapper<>();
    LambdaQueryWrapper<TblEmployee> eq = queryWrapper.lambda().eq(TblEmployee::getCorpId, 2222);
    List<TblEmployee> tblEmployees = dao.selectList(eq);
    tblEmployees.forEach(p -> {
        p.setEmployeeNumber(String.format("P%s", p.getEmployeeNumber()));
        dao.updateById(p);
    });
}

结果运行发现抛异常如下:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'MP_OPTLOCK_VERSION_ORIGINAL' not found. Available parameters are [param1, et]

	at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:92)
	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:440)

查阅资料后,发现需要注入一个拦截器OptimisticLockerInterceptor

@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {

    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}

我用的版本是3.4.0,发现这个拦截器已经弃用,建议使用MybatisPlusInterceptor,使用OptimisticLockerInterceptor虽然能够解决问题,但是不够完美。

使用MybatisPlusInterceptor的方法:

 @Bean
 public MybatisPlusInterceptor optimisticLockerInterceptor() {
     MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
     interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); 
     return interceptor;
 }

最后运行,查看日志可以发现乐观锁已经生效:

posted @ 2021-02-20 10:32  划破黑夜  阅读(7867)  评论(0编辑  收藏  举报