Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction
Using REQUIRES_NEW
is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED
- it will create a new transaction.
That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional
, it will create a new transaction.
So, with that in mind, if using REQUIRES_NEW
makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.
On rollback - using REQUIRES_NEW
will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations.
Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.
If you really need to do it in separate transaction you need to use REQUIRES_NEW
and live with the performance overhead. Watch out for dead locks.
I'd rather do it the other way:
- Validate data on Java side.
- Run everyting in one transaction.
- If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
- Write good unit tests.