@Transactional
is an annotation in Java used to manage database transactions automatically. It makes sure that a series of operations either all succeed or all fail, keeping the database consistent.
Why Use @Transactional
?
Imagine you are doing multiple steps that involve changing the database, like transferring money from one bank account to another. You want to ensure that both the withdrawal from one account and the deposit to another account happen together. If one fails, the other shouldn't happen either. This is where @Transactional
helps.
❓ How Does @Transactional
Work?
- Marks Methods or Classes: You put the
@Transactional
annotation above methods or classes where you want to ensure transaction management. - Handles Transactions Automatically: Spring takes care of starting a transaction before the method runs and committing it if everything goes well. If an error occurs, it rolls back the transaction, undoing any changes made during the method's execution.
Basic Example
import org.springframework.transaction.annotation.Transactional;
public class BankService {
@Transactional public void transferMoney(Account fromAccount, Account toAccount, double amount) { // Deduct amount from fromAccount fromAccount.debit(amount);
// Add amount to toAccount toAccount.credit(amount);
}
}
In this example, transferMoney
is marked with @Transactional
. This means:
- If the method completes without errors, changes are saved to the database.
- If an error occurs (e.g., if fromAccount
doesn't have enough money), all changes are undone.
❓ How Spring Manages It
- Proxy Creation: Spring creates a proxy (a special object) for the class with
@Transactional
methods. - Transaction Interception: The proxy intercepts method calls to handle the transaction logic:
- Starts a transaction before the method runs.
- Commits the transaction if the method completes successfully.
- Rolls back the transaction if the method throws an error.