天天看點

MP實戰系列(十七)之樂觀鎖插件

聲明,目前隻是僅僅針對3.0以下版本,2.0以上版本。

意圖:

當要更新一條記錄的時候,希望這條記錄沒有被别人更新

樂觀鎖實作方式:

取出記錄時,擷取目前version
更新時,帶上這個version
執行更新時, set version = yourVersion+1 where version = yourVersion
如果version不對,就更新失敗
           

第一步,配置

SSM架構(Spring+SpringMVC+MyBatis-Plus):

spring-mybatis.xml配置:

SpringBoot配置:

@Bean

public OptimisticLockerInterceptor optimisticLockerInterceptor() {
    return new OptimisticLockerInterceptor();
}
           

第二步,加上注解

public class User {

@Version
private Integer version;
           

}

特别說明: 僅支援int,Integer,long,Long,Date,Timestamp

測試代碼:

int id = 100;

int version = 2;

User u = new User();

u.setId(id);

u.setVersion(version);

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;