Transactions
A transaction is a set of operations that form an indivisible unit of work. These operations either all succeed together or all fail together.
Operations:
- Start Transaction: Begin the set of operations. (start transaction / begin)
- Commit Transaction: Finalize the operations if all succeed. (commit)
- Rollback Transaction: Revert all operations if any step fails. (rollback)
Assume you need to delete a department and then delete all employees in that department:
| |
In the example above, you’d end up with employees belonging to a non-existent department, causing data inconsistency.
Spring Transaction Management
Annotation: @Transactional.
Placement: Service layer methods, classes, or interfaces.
What it does: Hands over the method to Spring for transaction management. It starts a transaction before execution, commits upon successful completion, and rolls back if an exception occurs.
Updated method:
| |
You can also enable transaction logs in your configuration:
| |
Transaction Attributes - Rollback
By default, Spring only rolls back for RuntimeException. Use the rollbackFor attribute to specify which exception types should trigger a rollback.
| |
Transaction Attributes - Propagation
Transaction propagation defines how a transaction behaves when one transactional method calls another.
| |
When a calls b, propagation determines whether b joins a’s transaction or starts its own.
This is controlled via the propagation attribute:
| Attribute Value | Description |
|---|---|
| REQUIRED (Default) | Requires a transaction. Joins existing if present; creates new if not. |
| REQUIRES_NEW | Always creates a new transaction, suspending the existing one if present. |
| SUPPORTS | Supports transaction. Joins if present; runs without transaction if not. |
| NOT_SUPPORTED | Does not support transaction. Suspends existing; runs without transaction. |
| MANDATORY | Must have an existing transaction, otherwise throws an exception. |
| NEVER | Must not have a transaction, otherwise throws an exception. |
Example usage:
| |