1.配置插件
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:
- 取出记录时,获取当前 version
- 更新时,带上这个 version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果 version 不对,就更新失败
spring boot 注解方式:
// Spring Boot 方式
@Configuration
@MapperScan("com.cy.springboot.mapper")
public class MybatisPlusConfig {
//乐观锁插件
@Bean
public MybatisPlusInterceptor OptimisticLockerInnerInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
2.在实体类的字段上加上@Version注解
@Version
private Integer version;
测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceTests {
@Resource
private IUserService userService;
@Test
public void testCAS() {
//线程1 age:22 version:1
User user1 = userService.getById(26);
//线程2 age:22 version:1
User user2 = userService.getById(26);
user1.setAge(100);
user2.setAge(80);
//update 100 version:2 where version1=数据库version1
System.out.println(userService.updateById(user1));
//update 100 version:2 where version1=数据库version2
System.out.println(userService.updateById(user2));
}
}
本文介绍了如何在SpringBoot应用中使用MyBatisPlus实现乐观锁,通过配置插件和在实体类中添加@Version注解,确保更新记录时的并发安全性。在测试中展示了两个并发线程尝试更新同一记录的不同场景。
624

被折叠的 条评论
为什么被折叠?



