mybatis-plus 添加乐观锁?
Mybatis-Plus 提供了乐观锁的支持,可以通过 @Version 注解来实现乐观锁。
- 在实体类中添加
@Version注解:
@Data
public class User {
private Long id;
private String name;
private Integer age;
@Version
private Integer version;
}
- 在 Mapper 中使用
@Update注解,并指定使用乐观锁:
public interface UserMapper extends BaseMapper<User> {
@Update("update user set name=#{name}, age=#{age}, version=version+1 where id=#{id} and version=#{version}")
int updateWithOptimisticLock(User user);
}
在更新操作时,需要同时指定 id 和 version,保证更新的是正确的数据,并且将版本号加一。如果更新失败,说明数据已经被其他进程更新,需要进行相应的处理。
- 使用 Mybatis-Plus 提供的乐观锁插件:
Mybatis-Plus 也提供了乐观锁插件,可以在全局配置中开启:
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
开启后,在更新操作时,Mybatis-Plus 会自动添加乐观锁的校验。如果更新失败,会抛出 OptimisticLockException 异常
原文地址: https://www.cveoy.top/t/topic/deZp 著作权归作者所有。请勿转载和采集!