Annotation Interface Transactional
When a method annotated with @Transactional is executed, it will automatically be wrapped in a database transaction. The transaction will be committed if the method completes normally, or rolled back if an exception is thrown.
Usage examples:
// Basic usage - starts a new transaction or joins existing one
@Transactional
public void saveUser(User user) {
userRepository.save(user);
auditRepository.log("User saved: " + user.getName());
}
// Always create a new transaction
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void logAudit(String message) {
auditRepository.log(message);
}
// Read-only transaction (may allow optimizations)
@Transactional(readOnly = true)
public List<User> findAllUsers() {
return userRepository.findAll();
}
// Custom rollback rules
@Transactional(rollbackFor = {BusinessException.class})
public void processOrder(Order order) throws BusinessException {
// ...
}
Important:
- Self-invocation (calling a @Transactional method from within the same class) bypasses the proxy
- Only public methods can be transactional
- The class must not be final (CGLIB limitation)
- Since:
- 6.2.0
- Author:
- wisdomme
- See Also:
-
Optional Element Summary
Optional ElementsModifier and TypeOptional ElementDescriptionThe transaction isolation level.Exception types that should NOT trigger a rollback.The transaction propagation behavior.booleanWhether the transaction is read-only.Exception types that should trigger a rollback.intThe transaction timeout in seconds.
-
Element Details
-
propagation
Propagation propagationThe transaction propagation behavior.Defaults to
Propagation.REQUIRED, which joins an existing transaction or creates a new one if none exists.- Returns:
- the propagation behavior
- Default:
REQUIRED
-
isolation
Isolation isolationThe transaction isolation level.Defaults to
Isolation.DEFAULT, which uses the database's default isolation level.- Returns:
- the isolation level
- Default:
DEFAULT
-
timeout
int timeoutThe transaction timeout in seconds.Defaults to -1 (no timeout / use database default).
- Returns:
- the timeout in seconds
- Default:
-1
-
readOnly
boolean readOnlyWhether the transaction is read-only.A read-only transaction may allow database optimizations and is useful for methods that only query data.
- Returns:
- true if read-only
- Default:
false
-
rollbackFor
Exception types that should trigger a rollback.By default, transactions are rolled back for RuntimeException and Error. Specify additional exception types here if needed.
- Returns:
- exception types to rollback for
- Default:
{}
-
noRollbackFor
Exception types that should NOT trigger a rollback.Use this to prevent rollback for specific exceptions that would normally cause a rollback.
- Returns:
- exception types to not rollback for
- Default:
{}
-