Junior — Middle
What to do if a nested transaction ends with an error, and the outer transaction is suspended at this time?
sobes.tech AI
Answer from AI
In Java, if a nested transaction ends with an error and the outer transaction is suspended, usually the entire outer transaction is rolled back along with the nested one. This is because nested transactions in most transaction manager implementations (e.g., Spring) are not fully independent — they operate within the scope of a single outer transaction.
What to do in such a situation:
- Handle the error in the nested transaction and explicitly call rollback if necessary.
- If the nested transaction should be independent, use a separate transactional context (for example, with propagation = REQUIRES_NEW) so that errors in the nested transaction do not affect the outer one.
- Otherwise, an error in the nested transaction will also cause the outer transaction to rollback.
Example with Spring:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void nestedTransaction() {
// code of the nested transaction
if (error) {
throw new RuntimeException("Error in nested transaction");
}
}
@Transactional
public void outerTransaction() {
try {
nestedTransaction();
} catch (Exception e) {
// error handling
}
// further code
}
Thus, to prevent the outer transaction from rolling back due to an error in the nested one, you need to use a separate transactional context.