【发布时间】:2019-03-02 07:37:06
【问题描述】:
我正在学习 Spring JPA 和 Hibernate。所以我遇到了一个问题。
我有这个方法
@Transactional(isolation = Isolation.REPEATABLE_READ)
public void sendMoney(Long from, Long to, Double amount) {
WalletEntity fromWallet = walletServiceImpl.getWallet(from);
WalletEntity toWallet = walletServiceImpl.getWallet(to);
fromWallet.setAmount(fromWallet.getAmount() - amount);
toWallet.setAmount(toWallet.getAmount() + amount);
TransactionEntity transaction = new TransactionEntity();
transaction.setAmount(amount);
transaction.setToWallet(toWallet);
transaction.setFromWallet(fromWallet);
transactionRepository.saveAndFlush(transaction);
}
我想测试它并创建了这个:
@GetMapping("/send")
public void sendMoney() {
ExecutorService executorService = Executors.newFixedThreadPool(20);
for (int i = 0; i < 100; i++) {
executorService.execute(() -> {
accountServiceImpl.sendMoney(1L, 2L, 10D);
});
}
}
所以当我阅读钱包时,我得到了旧值,但我做了Isolation.REPEATABLE_READ。数据库中的值当然是错误的。
你能解释什么是错的吗?谢谢!
【问题讨论】:
-
数据库值错误是什么意思?
-
我执行了 100 次,从钱包 1 到钱包 2 拿了 10 个“钱”。我期望钱包 1 的价值少 1000,钱包 2 的价值多 1000。但是少了大约 200-300 个。
-
改用“Isolation.READ_COMMITTED”
标签: java database spring spring-data-jpa isolation-level