A money transfer changes two account balances. If one change succeeds and the other fails, the data can become inconsistent. Spring’s @Transactional annotation marks a method or class for managed transactions, so related changes can be committed together or rolled back. section 13.3 section 13.5
Place @Transactional on the service method that performs the use case. Spring supplies an aspect that intercepts the method call, starts a transaction, and commits or rolls it back. An aspect is code that intercepts a method’s execution to apply additional behavior. section 13.2 section 13.3
Transfer between accounts
A transactional transferMoney method reads the sender and receiver, subtracts the amount from one balance, and adds it to the other. A successful transfer of 100 from two accounts initially holding 1,000 leaves balances of 900 and 1,100. If the method instead throws a runtime exception after updating both balances, Spring rolls back the changes. 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
}
}The service method is annotated with @Transactional and deliberately throws a runtime exception after both updates to demonstrate rollback. section 13.3
You can also put @Transactional on a class to make its methods transactional. Choose the method-level annotation when the transaction should mark a particular operation; the class-level annotation applies it across the class. section 13.3 section 13.5
Exception handling matters for the default rollback behavior:
- An uncaught runtime exception must leave the transactional method for the aspect to see it and roll back. section 13.2
- If the method catches and handles the exception without throwing it further, the aspect cannot see it; the transaction can commit. section 13.2
- A checked exception does not cause rollback by default. section 13.2
Figure 13.5 If a runtime exception is thrown inside the method, but the method treats the exception and doesn’t throw it back to the caller, the aspect won’t get this exception and will commit the transaction. When you treat an exception in a transactional method, such as in this case, you need to be aware the transaction won’t be rolled back, as the aspect managing the transaction cannot see the exception.

This diagram contrasts an exception occurring inside a method with an exception reaching the transaction aspect. section 13.2



