Spring Data JPA:无法读取更新的值

时间:2016-01-07 06:22:03

标签: spring spring-boot spring-data-jpa

我们正在使用SpringBoot及其弹簧数据JPA,但有些事情发生了:

我们在这里有两种不同的服务:

ServiceA:

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

ServiceB:

// 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);
        }

有什么想法吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

您是否尝试使用saveAndFlush代替save

例如:

ConsumerBalance consumerBalance = consumerBalanceRepository
                .findByConsumerId(consumerId);
if (null == consumerBalance) {
   // something not cool
consumerBalance.setVersion(1);
consumerBalanceRepository.saveAndFlush(consumerBalance);
}

另外,你有服务缓存吗?如果是,您还需要刷新缓存。