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;
 }

最后運行,查看日志可以發現樂觀鎖已經生效:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM