mybatis plus樂觀鎖
阿新 • • 發佈:2020-12-21
給實體欄位新增@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); }