意图:
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:
乐观锁配置需要2步 记得两步
spring xml:
<bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>
spring boot:
@Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); }
@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
原文:https://www.cnblogs.com/song1024/p/13297280.html