Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

前端 未结 2 466
青春惊慌失措
青春惊慌失措 2021-01-29 23:38

I have a method that has the propagation = Propagation.REQUIRES_NEW transactional property:

@Transactional(propagation = Propagation.REQUIRES_NEW)
p         


        
相关标签:
2条回答
  • 2021-01-30 00:07

    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.
    0 讨论(0)
  • 2021-01-30 00:15

    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.

    0 讨论(0)
提交回复
热议问题