17 樂觀鎖插件

主要適用場景

意圖:
當要更新一條記錄的時候,希望這條記錄沒有被別人更新

樂觀鎖實現方式:

  1. 取出記錄時,獲取當前version
  2. 更新時,帶上這個version
  3. 執行更新時, set version = newVersion where version = oldVersion
  4. 如果version不對,就更新失敗

樂觀鎖配置

  1. 插件配置
    spring xml
<bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>

spring boot:

@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
    return new OptimisticLockerInterceptor();
}
  1. 註解實體字段 @Version 必須要!
@Version
private Integer version;

特別說明:
支持的數據類型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
整數類型下 newVersion = oldVersion + 1
newVersion 會回寫到 entity 中
僅支持 updateById(id) 與 update(entity, wrapper) 方法
在 update(entity, wrapper) 方法下, wrapper 不能複用!!!

示例

int id = 100;
int version = 2;

User u = new User();
u.setId(id);
u.setVersion(version);
u.setXXX(xxx);

if(userService.updateById(u)){
    System.out.println("Update successfully");
}else{
    System.out.println("Update failed due to modified by others");
}

示例SQL原理

update tbl_user set name = 'update',version = 3 where id = 100 and version = 2
發佈了66 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章