【发布时间】:2016-04-11 10:54:54
【问题描述】:
我们正在使用 SpringBoot 及其 Spring Data JPA,但发生了一些连线问题:
我们在这里有两种不同的服务:
服务A:
ConsumerBalance consumerBalance = consumerBalanceRepository.findByConsumerId(consumerId);
// original consumer balance is 3.0
// update balance, e.g. balance = 4.0
// then save consumerBalance to data base using JPARepository.save
服务B:
// After the operation ServiceA, we execute ServiceB
ConsumerBalance consumerBalance = consumerBalanceRepository.findByConsumerId(consumerId);
// print consumerBalance, the result is still 3.0, not the updated value 4.0
服务事务注解:
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
public class ConsumerBalanceServiceImpl implements ConsumerBalanceService
JAPRepository:
public interface ConsumerBalanceRepository extends JpaRepository<ConsumerBalance,Long>{
ConsumerBalance findByConsumerId(Long consumerId);
更新
它们在不同的事务中,ServiceB 在 ServiceA 提交后执行,而在 ServiceA 之后,更新的数据实际上是刷新到数据库(我使用断点来检查)
更新
数据更新代码
ConsumerBalance consumerBalance = consumerBalanceRepository
.findByConsumerId(consumerId);
if (null == consumerBalance) {
consumerBalance = new ConsumerBalance();
// something not cool
consumerBalance.setVersion(1);
consumerBalanceRepository.save(consumerBalance);
}
有什么想法吗?提前致谢!
【问题讨论】:
-
请添加执行实际值更新和保存的代码,而不是 cmets 描述它的代码。
-
是同一个事务,还是不同的事务?如果 ServiceB 在 ServiceA 提交之前执行,这是可以预料的。
-
@mavarazy 它们在不同的事务中,ServiceB 在 ServiceA 提交后执行,而在 ServiceA 之后,更新的数据实际上是刷新到数据库(我使用断点检查)
-
@MrROY 你在 Spring 中使用了一些缓存机制吗?你查询DB,值是4,对吧?
-
@mavarazy 是的,ServiceA执行后,值变成了4,但是ServiceA在程序中还是得到了3.0,连线!
标签: spring spring-boot spring-data-jpa