第一步

在后台进行配置(基于SpringBoot的配置)

//    乐观锁
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    // 向MyBatis-Plus的过滤器链中添加分页拦截器,需要设置数据库类型(主要用于分页方言)
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    // 添加乐观锁拦截器
    interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
    return interceptor;
}

第二步

在entity类中加入@Version注解(注意!!!!)

//    @Version    乐观锁
    @Version
    private Integer version;

第三步

在数据库中加入version字段(一定要确保实体类中的字段与数据库中的对照

ALTER TABLE sdt_message
ADD COLUMN version int(10) NULL AFTER student_hobby;
UPDATE sdt_message set version=1;

第四步

编写测试类

    @Test
    public void getUpdate() {

        Role role = roleMapper.selectById(2);
        role.setId(2);
        role.setStudentName("呦呦呦");
        role.setVersion(role.getVersion());//当前版本信息
        role.updateById();
    }

心得:version字段数值默认为1,每次测试version自动+1,如果没有+1则两种可能:1.数据库字段与entity类中的version字段不对照。2.@Version注释为启用。

posted on 2022-09-30 10:14  园来个园  阅读(665)  评论(0)    收藏  举报