什么是乐观锁:
就是我们每一次操作数据后,我们就会更改他的版本号,当另外的线程若想要对该数据进行操作,检查版本号是否与自己获得的版本号一致,如果不一致,那么我们就会取消该操作。
在mybatis-plus中,我们使用注解@Version标注我们表类的一个属性,使之成为我们的版本号。我们每一次对该表操作就会令他自增1.
例子:
①、注解我们的版本号
@Data
@TableName("t_product")
public class Product {
private Long id;
private String name;
private Integer price;
// 表示这个为版本号
@Version
private Integer version;
}
②、添加我们的乐观锁拦截器
@MapperScan("com.atguigu.mybatisplus.mapper")
@Configuration
public class mybatisConfig {
@Bean
public MybatisPlusInterceptor MPI(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
// mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
}
③、测试:
@SpringBootTest
public class postiveLockTest {
@Autowired
productMapper productMapper;
// @Transactional
@Test
public void test(){
//他们查询的价格:
Product WangProduct = productMapper.selectById(1);
System.out.println("小王查询的价格:" + WangProduct.getPrice());
Product LiProduct = productMapper.selectById(1);
System.out.println("小李查询的价格:" + LiProduct.getPrice());
//小王将价格上升50
WangProduct.setPrice(WangProduct.getPrice()+50);
productMapper.updateById(WangProduct);
//小李将价格下降30
LiProduct.setPrice(LiProduct.getPrice()-30);
// 此时修改会不成功,因为小李获得的版本号与目前库里的版本号不同,所以我们就无法进行修改
int Updateresult = productMapper.updateById(LiProduct);
System.out.println("是否可以修改:" + Updateresult);
// 改良:判断是否斯修改成功,不成功再次获得进行修改
if (Updateresult == 0){
Product Newproduct = productMapper.selectById(1);
Newproduct.setPrice(Newproduct.getPrice() -30);
System.out.println("新的价格"+ Newproduct.getPrice());
productMapper.updateById(Newproduct);
}
Product Bossproduct = productMapper.selectById(1);
System.out.println("boss查询的价格为:"+Bossproduct.getPrice());
}
}