Propagation behavior is a feature of Spring transaction management that determines how a transaction should propagate from one method to another method in the same or different transactional context. It specifies the behavior of a transactional method when it executes in the context of an existing transaction.
Spring supports 7 different propagation behaviors:
1. REQUIRED propagation: This is the default behavior in Spring, which means that the transaction must be started in the calling method. If an existing transaction is available, it will be used. Otherwise, a new transaction will be created. This behavior ensures that a transaction is created for each method call that requires it.
2. REQUIRES_NEW propagation: This behavior always creates a new transaction, regardless of whether an existing transaction is already available or not. If an existing transaction is present, it will be suspended until the new transaction completes its execution. After that, the old transaction will be resumed.
3. SUPPORTS propagation: With this behavior, the method is executed within a transaction if one is already present. Otherwise, the method is executed without a transaction. In other words, if the calling method has an active transaction, it will be used. Otherwise, the method will be executed without a transaction.
4. MANDATORY propagation: This behavior mandates that an active transaction must already be present when the method is called. If an active transaction is not available, an exception is thrown.
5. NOT_SUPPORTED propagation: With this behavior, the method is executed without a transaction. If an active transaction is present, it will be suspended until the method completes its execution.
6. NEVER propagation: This behavior mandates that a transaction must not be present when the method is called. If an active transaction is already available, an exception is thrown.
7. NESTED propagation: This behavior creates a nested transaction, which can be rolled back or committed independently of the outer transaction. If an existing transaction is present, the method can be executed within the context of that transaction. Otherwise, a new transaction will be created. If the outer transaction is rolled back, the nested transaction will also be rolled back. If the nested transaction is rolled back, the outer transaction can still continue.
Hereβs an example of the REQUIRED propagation behavior:
@Transactional(propagation = Propagation.REQUIRED)
public void updateCustomer(Customer customer) {
// perform some database operations
}
In this example, the method updateCustomer is annotated with @Transactional and its propagation behavior is set to REQUIRED. This means that if an existing transaction is not already available, a new transaction will be created for this method to perform its operations. If a transaction is already available, it will use the existing transaction.