主要適用場景
意圖:
當要更新一條記錄的時候,希望這條記錄沒有被別人更新
樂觀鎖實現方式:
- 取出記錄時,獲取當前version
- 更新時,帶上這個version
- 執行更新時, set version = newVersion where version = oldVersion
- 如果version不對,就更新失敗
樂觀鎖配置
- 插件配置
spring xml
<bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>
spring boot:
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
- 註解實體字段 @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