Senior
Tell us about the @Transactional annotation, how can a transaction be configured through it?
sobes.tech AI
Answer from AI
The @Transactional annotation in Java (commonly in the Spring Framework) is used for declarative transaction management. It allows you to specify that a method or class should be executed within a transaction and sets the transaction behavior parameters.
With @Transactional, you can configure:
- propagation — the transaction propagation mode (e.g., REQUIRED, REQUIRES_NEW).
- isolation — the transaction isolation level (READ_COMMITTED, SERIALIZABLE, etc.).
- readOnly — optimization for read-only operations.
- timeout — the maximum execution time of the transaction.
- rollbackFor / noRollbackFor — exceptions that cause the transaction to rollback or not.
Example:
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public void updateData() {
// business logic with transaction
}
This simplifies transaction management without the need to write explicit code for beginning, committing, or rolling back.