Video in progress
If a `@Transactional` method calls a `REQUIRES_NEW` method, what happens to the persistence context and the entities?
REQUIRES_NEW suspends the outer transaction and opens a new connection and a new persistence context. An entity loaded in the outer method is not managed in the inner transaction, and a change made inside doesn't show up on the copy in the outer context.
📖 Answer
An example: an audit record has to be saved even if there's an error:
@Transactional
public void pay(Long orderId) {
Order order = orders.findById(orderId).orElseThrow();
audit.log(order, "PAY_STARTED"); // REQUIRES_NEW
order.markPaid();
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void log(Order order, String action) {
auditRepo.save(new AuditRecord(order.getId(), action));
order.setLastAction(action); // this change is not saved here
}
In the inner transaction, order belongs to a different persistence context. Changing it does nothing at the inner commit, because dirty checking only looks at entities in its own context. At the outer transaction's commit, though, lastAction may get saved, since it's that same object. The result is confusing: which transaction saves the change isn't clear from the code.
Two more things:
REQUIRES_NEWtakes a second connection. If the pool is small and many requests go through this path at once, they all hold their first connection and wait for a second one, which is a pool deadlock.- If the inner method is called from the same class (
this.log(...)), the Spring proxy doesn't kick in andREQUIRES_NEWisn't applied at all.
That's why you should pass the inner transaction ids and plain values, not entities. If needed, reload the entity inside.
Sign up to mark studied questions and save your progress.