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

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

  • 相关阅读:
    c#反射动态创建窗体
    ImageSwitcher 图片切换器
    viewSwitcher 切换视图
    ratingBar 星级评分条
    seekBar拖动滑块
    pythonUDP发送结构体,对齐到C++结构体
    pyqt5界面
    progressbar
    SVN服务器搭建和使用(一)
    关于MBR、GPT以及BIOS引导模式区分
  • 原文地址:https://www.cnblogs.com/wugang/p/14419552.html
Copyright © 2020-2023  润新知