我很难理解如何决定用 Spring @Transaction 注释哪些方法。
BankService {
transfer(Account from, Account to, int amount){
deduct(from, amount);
deposit(to, amount);
}
deduct(Account account, int amount){
account = accountRepo.load(account); //make sure we dont have an old reference with old balance
int balance = account.getBalance();
if (balance<amount){
throw new IllegalStateException("Not enough money");
} else {
account.setBalance(balance-amount);
accountRepo.save(account);
}
}
deposit(Account account, int amount){
account = accountRepo.load(account); //make sure we dont have an old reference with old balance
account.setBalance(account.getBalance() + amount);
accountRepo.save(account);
}
}
在一次转账中,如果扣款失败,那么即使存款没有失败,显然也不应该继续扣款。
在五种方法(转账、扣款、存款、加载、保存)中,哪些应该用@Transactional 注释,为什么?