在项目中添加乐观锁的插件:
@Configuration
@MapperScan("com.demo.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加分页插件并指定数据库的类型
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//添加乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
给实体类添加相应的乐观锁版本号注解:
@Data
public class Product {
private Long id;
private String name;
private Integer price;
@Version //表示乐观锁版本号字段
private Integer version;
}
测试代码展示:
@Test
public void testProduct01(){
// 小李查询商品价格
Product productLi = productMapper.selectById(1L);
System.out.println("小李查询的商品价格"+productLi.getPrice());
//小王查询商品价格。
Product productWang = productMapper.selectById(1L);
System.out.println("小王查询的商品价格"+productWang.getPrice());
// 小李将价格加50
productLi.setPrice(productLi.getPrice()+50);
productMapper.updateById(productLi);
// 小王将价格-30
productWang.setPrice(productWang.getPrice()-30);
int i = productMapper.updateById(productWang);
System.out.println("result= " + i);
//老板查询商品价格
Product productLaoBan = productMapper.selectById(1L);
System.out.println("老板查询的商品价格"+productLaoBan.getPrice());
}
上面的代码只有小王更新价格的操作可以实现,小李更新价格的操作不会执行
@Test
public void testProduct01(){
// 小李查询商品价格
Product productLi = productMapper.selectById(1L);
System.out.println("小李查询的商品价格"+productLi.getPrice());
//小王查询商品价格。
Product productWang = productMapper.selectById(1L);
System.out.println("小王查询的商品价格"+productWang.getPrice());
// 小李将价格加50
productLi.setPrice(productLi.getPrice()+50);
productMapper.updateById(productLi);
// 小王将价格-30
productWang.setPrice(productWang.getPrice()-30);
int i = productMapper.updateById(productWang);
System.out.println("result= " + i);
if(i==0){
Product productNew = productMapper.selectById(1L);
productNew.setPrice(productNew.getPrice()-30);
productMapper.updateById(productNew);
}
//老板查询商品价格
Product productLaoBan = productMapper.selectById(1L);
System.out.println("老板查询的商品价格"+productLaoBan.getPrice());
}
这段代码完善了更新操作小王将价格更新完毕之后才会执行小李更新价格的操作。