A money transfer needs two changes: subtract money from one account and add it to another. If only the first change succeeds, money disappears. A database transaction groups related data changes so they succeed together or none take effect. This all-or-nothing property is called atomicity. section 13.0 section 13.1
A $100 transfer
John starts with $1,000 and Jane with $500. A successful transfer leaves John with $900 and Jane with $600. If the deposit fails after the withdrawal, the transaction rolls back, restoring their starting balances instead of leaving John $100 short. section 13.1
A transaction can end in two ways:
- Commit: all required steps succeed, and their changes are persisted. section 13.1
- Rollback: the changes are reverted to avoid leaving partial results. section 13.1
In a Spring application, mark the service method that performs the complete operation with @Transactional. Spring provides an aspect that intercepts the method call, starts a transaction, and applies commit or rollback logic. The transfer service can then use a repository to change both account records within that transaction. section 13.2 section 13.3
Listing 13.11 Simulating a problem occurs during the use case execution
@Service
public class TransferService {
// Omitted code
@Transactional
public void transferMoney(
long idSender,
long idReceiver,
BigDecimal amount) {
Account sender = accountRepository.findAccountById(idSender);
Account receiver = accountRepository.findAccountById(idReceiver);
BigDecimal senderNewAmount = sender.getAmount().subtract(amount);
BigDecimal receiverNewAmount = receiver.getAmount().add(amount);
accountRepository.changeAmount(idSender, senderNewAmount);
accountRepository.changeAmount(idReceiver, receiverNewAmount);
throw new RuntimeException("Oh no! Something went wrong!"); #A
}
}This transfer method updates both accounts and then deliberately throws a runtime exception, allowing you to observe rollback. section 13.3
By default, Spring rolls back when the transactional method throws a runtime exception to its caller. If the method catches the exception and does not rethrow it, the aspect cannot see it and may commit instead. A checked exception does not trigger rollback by default. section 13.2




















