mybatis plus乐观锁

给实体字段添加@Version注解,数据库表中添加version字段

注意:

  • 支持的数据类型只有: int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下 newVersion = oldVersion + 1
  • newVersion 会回写到 entity
  • 仅支持 updateById(id)update(entity, wrapper) 方法
  • update(entity, wrapper) 方法下, wrapper 不能复用!!!
@Data
@TableName("spider_process_monitor")
public class QueryProcessPojo {

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    @TableField("project_name")
    private String projectName;
    @TableField("is_disabled")
    private Integer disabled;
    @TableField("last_updated")
    private Date lastUpdated;
    @Version
    private Integer version;
}

配置类里注册插件OptimisticLockerInnerInterceptor

这里使用MybatisPlusInterceptor是因为3.4.0版本以后,其他方法都被弃用,强行使用会报错

@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

}

使用乐观锁

注意:

必须去数据库查询一下再更新,否则乐观锁不生效,重要!,重要!,重要!

public Integer disableProject(String projectName, Integer disabled) {
        // 必须去数据库查询一下,否则乐观锁不生效
        QueryProcessPojo queryProcessPojo = this.getProjectByName(projectName);
        if (projectName==null){
            return 0;
        }
        return mapper.updateById(queryProcessPojo);
    }
posted @ 2020-12-21 18:45  rm-rf*  阅读(87)  评论(0编辑  收藏  举报