就是我们每一次操作数据后,我们就会更改他的版本号,当另外的线程若想要对该数据进行操作,检查版本号是否与自己获得的版本号一致,如果不一致,那么我们就会取消该操作。
本文介绍Mybatis-Plus的乐观锁插件的用法。
@Configuration public class MyBatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return mybatisPlusInterceptor; } }
版本号的字段上加注解
@Version private Integer version;
说明:
MP会把设置进去的版本号当作更新条件,并且版本号+1更新进去。
@Test public void update(){ User user = userMapper.getById(1L); user.setEmail("Test1111@email.com"); user.setUpdateTime(LocalDateTime.now()); int update = userMapper.updateById(user); System.out.println(update); }
DEBUG==> Preparing: UPDATE sys_user SET email=?, update_time=?, version=? WHERE id=? AND version=? DEBUG==> Parameters: Test1111@email.com(String), 2019-09-19T16:00:38.149(LocalDateTime), 2(Integer), 1(Long), 1(Integer) DEBUG<== Updates: 1