Senior
What does the @Transactional annotation do and what are its attributes?
sobes.tech AI
Answer from AI
The @Transactional annotation in Java is used to manage transactions at the method or class level. It guarantees that all operations within a transaction are executed atomically: either all succeed or, in case of an error, a rollback occurs.
Main attributes of @Transactional:
- propagation — defines the transaction behavior when called from another transactional context (e.g., REQUIRED, REQUIRES_NEW).
- isolation — the transaction isolation level (READ_COMMITTED, SERIALIZABLE, etc.), affecting data visibility.
- timeout — the time to wait for the transaction to complete before it is interrupted.
- readOnly — indicates that the transaction is read-only, which can optimize database operations.
- rollbackFor / noRollbackFor — exception classes for which the transaction will or will not be rolled back.
Example:
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, timeout = 30, readOnly = false)
public void updateData() {
// business logic
}