实现MybatisPlus乐观锁

1、实体类中添加version字段及相关注解

@Version
@TableField(fill = FieldFill.INSERT)//第一次添加数据时使其有个默认值1
private Integer version;

2、添加配置类

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;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@Configuration
public class MyBatisPlusConfig {

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor( new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
}

3、接口请求(update set version = version + 1 where version = ?)

@ResponseBody
@GetMapping("/lock")
public Result lock() {
User user = userMapper.selectById(1);
user.setName("乐观锁");
userMapper.updateById(user);
return Result.success();
}

 

posted @ 2022-09-19 10:21  懂得归零  阅读(61)  评论(0编辑  收藏  举报