Skip to content

Commit

Permalink
Update optimistic-locker-plugin.md
Browse files Browse the repository at this point in the history
add doc for opt locker
  • Loading branch information
yuxiaobin authored Sep 18, 2018
1 parent 60f8606 commit 319fea3
Showing 1 changed file with 70 additions and 1 deletion.
71 changes: 70 additions & 1 deletion guide/optimistic-locker-plugin.md
Original file line number Diff line number Diff line change
@@ -1 +1,70 @@
# 乐观锁插件
# 乐观锁插件

## 主要适用场景

意图:

当要更新一条记录的时候,希望这条记录没有被别人更新

乐观锁实现方式:
* 取出记录时,获取当前version
* 更新时,带上这个version
* 执行更新时, set version = yourVersion+1 where version = yourVersion
* 如果version不对,就更新失败

**乐观锁配置需要2步 记得两步**

## 1.插件配置
spring xml
```xml
<bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>
```
spring boot
```java
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
```

## 2.注解实体字段 `@Version` 必须要!
```java
public class User {

@Version
private Integer version;

...
}
```

特别说明: **仅支持int,Integer,long,Long,Date,Timestamp,LocalDateTime**


## 示例

示例Java代码(参考[test case](https://gitee.com/baomidou/mybatis-plus-samples/tree/master/mybatis-plus-sample-optimistic-locker)代码)

```java
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原理

```text
update tbl_user set name='update',version=3 where id=100 and version=2;
```

0 comments on commit 319fea3

Please sign in to comment.