对于spring boot,我理解如果我有一个函数可以减少用户的平衡,我们可以在服务方法中使用@Transactional注解,如下所示:
@Transactional
public void reduceBalance(long userId, BigDecimal usage) {
...
}但我的问题并不是指将控件放在特定的函数上,我想知道的是:
public void updateAge(long userId, int newAge) {
User theUser = userRepository.findById(userId).orElse(null); // Line A-1
theUser.setAge(newAge); // Line A-2
userRepository.save(theUser); // Line A-3
}
public void updateName(long userId, String newName) {
User theUser = userRepository.findById(userId).orElse(null); // Line B-1
theUser.setName(newName); // Line B-2
userRepository.save(theUser); // Line B-3
}假设两个请求同时进入,A-1和B-1行同时执行,然后是A-2和B-2,然后是A-3和B-3。
B-3会覆盖A-2更改吗?如果是,这是不是意味着我们应该在每个服务中都使用@Transactional注解,或者实际上有更好的设计?
发布于 2020-04-20 00:50:32
强烈建议在每个服务中使用@Transaction,但如果您想通过不同的方式进行管理,另一种方法是使用@Version注解
Specifies the version field or property of an entity class that
serves as its optimistic lock value. The version is used to ensure
integrity when performing the merge operation and for optimistic
concurrency control.https://stackoverflow.com/questions/61306076
复制相似问题