MyBatisPlus使用Version注解(乐观锁)

您所在的位置:网站首页 version1 MyBatisPlus使用Version注解(乐观锁)

MyBatisPlus使用Version注解(乐观锁)

#MyBatisPlus使用Version注解(乐观锁)| 来源: 网络整理| 查看: 265

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 queryWrapper = new QueryWrapper(); LambdaQueryWrapper eq = queryWrapper.lambda().eq(TblEmployee::getCorpId, 2222); List 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; }

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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3