0
点赞
收藏
分享

微信扫一扫

9、Mybatis-Plus 乐观锁

文章目录

  • ​​1、使用场景​​
  • ​​2、乐观锁使用流程​​
  • ​​3、Mybatis-Plust 实现乐观锁​​
  • ​​3.1 修改实体类​​
  • ​​3.2、添加乐观锁插件配置​​
  • ​​3.3、流程测试​​
  • ​​3.4、测试结果​​

1、使用场景

9、Mybatis-Plus 乐观锁_mybatis-plus

2、乐观锁使用流程

9、Mybatis-Plus 乐观锁_分页_02

3、Mybatis-Plust 实现乐观锁

3.1 修改实体类

@Data
public class Product {
private Long id;
private String name;
private Integer price;
@Version
private Integer version;
}

3.2、添加乐观锁插件配置

@Configuration
//扫描mapper接口所在的包
@MapperScan("com.zyz.mybatisplus.mapper")
public class MyBatisPlusConfig {

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}

}

3.3、流程测试

@Test
public void test04(){
Product p1 = productMapper.selectById(1);
System.out.println("小李获得价格"+p1.getPrice());

Product p2 = productMapper.selectById(1);
System.out.println("小王获得价格"+p2.getPrice());

p1.setPrice(p1.getPrice()+50);
int rs1 = productMapper.updateById(p1);
System.out.println("小李操作的结果"+rs1);

p2.setPrice(p2.getPrice()-30);
int rs2 = productMapper.updateById(p2);
System.out.println("小王操作的结果"+rs2);
if(rs2 == 0){
p2 = productMapper.selectById(1L);
p2.setPrice(p2.getPrice()-30);
int rs = productMapper.updateById(p2);
}

Product p3 = productMapper.selectById(1L);
System.out.println("老板查看的结果"+p3.getPrice());

}

3.4、测试结果

9、Mybatis-Plus 乐观锁_分页_03


9、Mybatis-Plus 乐观锁_乐观锁_04


举报

相关推荐

0 条评论