1.实体类增加version属性配置
@Version
private Integer version;
2.数据表增加version版本字段
3.增加乐观锁插件
package net.xdclass.shopmanager.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
// 乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
4.使用
BannerDO bannerDO = new BannerDO();
bannerDO.setVersion(1);//旧版本号,即查询出来的版本号
bannerDO.setId(1);
bannerDO.setUrl("xdclass.net");
bannerMapper.updateById(bannerDO);
5.注意
- 乐观锁数据类型⽀持int、integer、long、timestamp
- 仅⽀持updateById和update⽅法