展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

乐观锁

@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());
}
posted @ 2022-07-20 15:04  DogLeftover  阅读(38)  评论(0编辑  收藏  举报