The Spring Framework provides a consistent and declarative approach for transaction management.
All that you need to do is to add @Transactional around the method to make it a single transaction:
@Transactional
void performTransfer(Account from, Account to, BigDecimal amount) {
@Transactional can be used at either a method or at a class level.
The following are some of the attributes you can specify on the @Transactional annotation:
- propagation: How does the transaction propagate? Should we continue an existing transaction, if one exists, or create a new transaction? The default is Propagation.REQUIRED.
- readOnly: Should the transaction be read-only?
- noRollbackForClassName: Which exceptions should not cause a rollback of a transaction?
- rollbackForClassName: Which exceptions should cause a rollback of a transaction?
- timeout: How long should we wait for a transaction to complete?
- isolation: What should be the isolation level for the transaction? The default is Isolation.DEFAULT.
- transactionManager: Identifies the transaction manager that manages this transaction.