Middle+
Tell me about the propagation types in the @Transactional annotation. Have you ever set non-default ones?
sobes.tech AI
Answer from AI
The @Transactional annotation in Spring has a propagation parameter that determines how a transaction should behave when a method is called within an existing transaction.
Main types of propagation:
REQUIRED(default): if there is a current transaction, the method runs within it; otherwise, a new one is created.REQUIRES_NEW: always creates a new transaction, suspending the existing one.SUPPORTS: if a transaction exists, use it; otherwise, execute without a transaction.NOT_SUPPORTED: always execute without a transaction, suspending the existing one.MANDATORY: must be called within a transaction; otherwise, an exception is thrown.NEVER: must be called outside a transaction; otherwise, an exception is thrown.NESTED: if a transaction exists, create a nested (savepoint) transaction; otherwise, behave likeREQUIRED.
Using non-default propagation is useful when you need to control transaction boundaries, for example:
REQUIRES_NEWfor independent operations so that errors in them do not roll back the main transaction.NESTEDfor partial rollback within a large transaction.
Example:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveAudit() {
// save audit independently of the main transaction
}