乐观锁
-
配置类
@Configuration
public class MybatisPlusOptLockerConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // 乐观锁插件
return interceptor;
}
}
- 实体类
@Data
public class User {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
@Version
private Integer version;
}
- 测试类
/**
* 批量更新带乐观锁
* <p>
* update(et,ew) et:必须带上version的值才会触发乐观锁
*
* SELECT COUNT( 1 ) FROM user WHERE (version = ?)
* 1(Integer)
*
* UPDATE user SET age=?, version=? WHERE (version = ?)
* 28(Integer), 2(Integer), 1(Integer)
*
* SELECT COUNT( 1 ) FROM user WHERE (version = ?)
* 1(Integer)
*
* SELECT COUNT( 1 ) FROM user WHERE (version = ?)
* 2(Integer)
*/
@Order(4)
@Test
public void testUpdateByEntitySucc() {
QueryWrapper<User> ew = new QueryWrapper<>();
ew.eq("version", 1);
long count = userMapper.selectCount(ew);
User entity = new User();
entity.setAge(28);
entity.setVersion(1);
// updated records should be same
Assertions.assertEquals(count, userMapper.update(entity, null));
ew = new QueryWrapper<>();
ew.eq("version", 1);
// No records found with version=1
Assertions.assertEquals(0, userMapper.selectCount(ew).intValue());
ew = new QueryWrapper<>();
ew.eq("version", 2);
// All records with version=1 should be updated to version=2
//Assertions.assertEquals(count, userMapper.selectCount(ew).intValue());
System.out.println(count + "--->" + userMapper.selectCount(ew).intValue());
}