gpt4 book ai didi

java - Spring JPA 无法在一个线程中正确处理多个事务

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:22:46 25 4
gpt4 key购买 nike

我有以下代码片段。在我调用 BatchSettleService.batchSettleWork(Array.asList([1,2,3])) 之后。我发现DB中的账户余额只减少了1。 debug的结果是每次accountRepository.findByIdForUpdate(2)返回的都是原来的Account,没有在过去的循环中操作过任何变化。我已经尝试了 Isolation.SERIALIZABLE 级别,但结果是一样的。我使用的数据库是 MySQL 5.7.20 InnoDb Engine。 JPA 实现是 Hibernate。我预计账户余额会减少 3. 我对交易的理解有问题吗?提前致谢!

@Service
public class BatchSettleService {

private Logger logger = LoggerFactory.getLogger(getClass());

@Autowired
private WorkSettleService workSettleService;

public List<WorkSettleResponse> batchSettleWork(List<Long> workIds) {
List<WorkSettleResponse> results= new ArrayList<>();
for(Long workId:workIds) {
try {
results.add(workSettleService.settleWork(new WorkSettleRequest(workId)));
} catch (WrappedException e) {
results.add(new WorkSettleResponse(workId,e.getErrCode(),e.getMessage()));
logger.error("Settle work failed for {}",workId,e);
}
}
return results;
}

}


public class WorkSettleService{

@Autowired
private AccountRepository accountRepository;

@Transactional(rollbackFor= {WorkSettleException.class,RuntimeException.class},propagation=Propagation.REQUIRES_NEW)
public WorkSettleResponse settleWork(WorkSettleRequest req){
Account account = accountRepository.findByIdForUpdate(2);
Integer balance = account .getBalance();
accountRepository.updateBalanceById(account.getId(),balance-1)
}
}


public interface AccountRepository extends Repository<Account, Integer> {

public Account findById(Integer id);

@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select ac from Account a where a.id = ?1")
public Account findByIdForUpdate(Integer id);

@Modifying
@Query("update Account a set a.balance = ?2 where a.id = ?1")
public int updateBalanceById(Integer id,Integer balance);

}

最佳答案

这个案子已经解决了。使用 account.setBalance(balance-1) 而不是 accountRepository.updateBalanceById(account.getId(),balance-1)。我不知道为什么 @Modifying annoation 不更新 EM 缓存,而 @Query 从 EM 缓存中获取数据,这对于 Spring JPA 实现来说有点奇怪。

关于java - Spring JPA 无法在一个线程中正确处理多个事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51280253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com