会当凌绝顶,一览众山小
| @Author:TTODS
MyBatisPlus框架系列文章目录:
-
MyBatisPlus之乐观锁(当前)
-
[MyBatisPlus之代码生成器(近期发布)]
前言
借助MybatisPlus,可以很轻松的实现乐观锁的使用
测试表
在之前中使用过的tag表中添加一个version
字段,且将其默认值设为0
在实体类中添加@Version注解
package com.example.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.Version;
import lombok.Data;
@Data
public class Tag {
@TableId(type = IdType.AUTO)
private Integer id;
private String name;
// @TableLogic 用来标注表示逻辑删除的字段 value是表示未删除的值 delval是表示删除的值
@TableLogic(value = "0",delval = "1")
private Integer isDelete;
@Version
private Integer version;
}
测试update方法
@SpringBootTest
@RunWith(SpringRunner.class)
public class CASTests {
@Resource
TagMapper mapper;
@Test
public void testCAS(){
Tag tag = mapper.selectById(3);
System.out.println(tag);
tag.setName("标签3_");
mapper.updateById(tag);
System.out.println(tag);
}
}
生成的sql语句及输出:
==> Preparing: SELECT id,name,is_delete,version FROM tag WHERE id=? AND is_delete=0
==> Parameters: 3(Integer)
<== Total: 1
Tag(id=3, name=标签3, isDelete=0, version=0)
==> Preparing: UPDATE tag SET name=?, version=? WHERE id=? AND version=? AND is_delete=0
==> Parameters: 标签3_(String), 1(Integer), 3(Integer), 0(Integer)
<== Updates: 1
Tag(id=3, name=标签3_, isDelete=0, version=1)
mybatis-plus
在生成update
语句时自动在set
语句中增加了version = 1(新值)
,在where子句中增加了version = 0(旧值)
.
而且在更新成功后,将传入的Tag对象的Version增加了1.
值得注意的是,mybatis-plus
的乐观锁仅支持updateById(entity)
方法和update(entity,wrapper)
方法.而且参数中必须传入原有的vserion
,不然是不会生效的.
上一篇:MyBatisPlus之逻辑删除
下一篇:MyBatisPlus之代码生成器(近期发布)