我们有以下使用spring-boot,spring-data-jpa的数据库更新场景(无需考虑保存),我们有两个数据表如下
- table_summary
{ "id": 1, "amount": 1000 }
// 认为是现有的汇总数据 - table_transaction
{ "id": 1, "amount": 1000 }
// 视为现有事务数据
现在我将更新摘要如下
恢复旧交易金额(因为我们有几个交易条目用于汇总)
{ "id": 1, "amount": 1000 }
SummaryRepository.java @Modifying @Transactional @Query("UPDATE Summary s SET s.amount=(s.amount - :oldTransactionAmount) WHERE s=:summary") void revertAmount(@Param(value = "oldTransactionAmount") BigDecimal oldTransactionAmount, @Param(value = "summary") Summary summary);
添加新的交易金额
{ "id": 1, "amount": 500 }
SummaryRepository.java @Modifying @Transactional @Query("UPDATE Summary s SET s.amount=(s.amount + :newAmount) WHERE s=:summary") void updateAmount(@Param(value = "newAmount") BigDecimal newAmount, @Param(value = "summary") Summary summary);
以下是 TransactionServiceImpl.java
@Autowired
private TransactionRepository transactionRepository;
@Autowired
private SummaryRepository summaryRepository;
@Override
@Transactional
private update(Transaction transaction //`{ "id": 1, "amount": 500 }`) {
Summary summary = this.summaryRepository.getOne(1); // This is sample picking summary `{ "id": 1, "amount": 1000 }`
Transaction oldTransaction = this.getOne(transaction.getId()); // `{ "id": 1, "amount": 1000 }`
this.summaryRepository.revertAmount(oldTransaction.getAmount(), @Param(value = "summary") Summary summary); // Updating summary to `0` ex. `1000 - 1000`
this.summaryRepository.updateAmount(transaction.getAmount(), @Param(value = "summary") Summary summary); // Updating summary to `500` ex. `0 + 500`
try {
this.transactionRepository.update(transaction);
// Again here i need summary record with update values
Summary summaryUpdated = this.summaryRepository.getOne(1);
// Here we need updated summary for some other purpose
System.out.println(summaryUpdated.getAmount()); // It's printing `1000` instead of `500`
} catch (RuntimeException e) {
log.error(e.getCause().getCause().getMessage(), e);
throw new ExceptionFactory().getExceptionInstance(e.getCause().getCause().getMessage(),
HttpStatus.CONFLICT);
}
}
@Override
public Transaction findById(long id) {
Transaction transaction = null;
try {
transaction = this.transactionRepository.findById(id).get();
} catch (RuntimeException e) {
log.error("No Transaction Data found for given Identifier :" + id, e);
throw new ExceptionFactory().getExceptionInstance("No Purchase Data found for given Identifier :" + id,
HttpStatus.INTERNAL_SERVER_ERROR);
}
return transaction;
}
但是在下面的行中,System.out.println(summaryUpdated.getAmount());
我们期望更新的金额,即500
我们得到的金额1000
是旧金额。