Junior — Middle
Can you explain the essence of the method marked with the Transactional annotation?
sobes.tech AI
Answer from AI
The @Transactional annotation in Java (usually in the Spring Framework) indicates that a method should be executed within a transaction. This means that all operations inside the method will be atomic: either all succeed and changes are saved, or if an error occurs, all changes are rolled back.
Main points:
- When entering the method, a new transaction is created or an existing one is used.
- If the method completes without exceptions, the transaction is committed.
- If an exception occurs, the transaction is rolled back.
Example:
@Transactional
public void transferMoney(Account from, Account to, BigDecimal amount) {
from.debit(amount);
to.credit(amount);
// if an error occurs here, changes will not be saved
}
This ensures data integrity and simplifies transaction management in applications.