MyBatis-Plus之乐观锁案例
1.数据库表中添加乐观锁标记字段
2.实体类中添加对应的字段,并用 @Version注解设定当前字段为乐观锁标记字段
package com.example.domain;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@Data
@TableName("users")
public class User {
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
@TableField(value = "name")
private String name;
@TableField(value = "number",select =false)
private String number;
@TableField(exist = false)
private Integer online;
@TableField(value = "deleted")
@TableLogic(value = "0",delval = "1")
private Integer deleted;
@Version
private Integer version;
}
3.在MyBatis-Plus配置类中添加乐观锁拦截器
package com.example.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MpConfig {
@Bean
public MybatisPlusInterceptor mpInterceptor() {
// 定义MyBatis-Plus拦截器
MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
// 添加乐观锁拦截器
mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mpInterceptor;
}
}
4.在修改操作中使用乐观锁
@Test
void update(){
User user = new User();
user.setId(2);
user.setNumber("123123");
user.setVersion(2);
userMapper.updateById(user);
}
注:一定要设置乐观锁的值,否则效果等效于没有使用乐观锁(没有设置乐观锁值的运行结果如下)