This is the 18th day of my participation in the August Challenge

I. Communication behavior of transactions

concept

  • Spring supports seven transaction propagation behaviors that determine the transaction boundary between the client and the called side
  • Complex transaction boundary control when multiple services with transaction control are called to each other
  • Transaction propagation behavior is a transaction-enhancing feature unique to the Spring framework and is not part of the actual transaction provider database behavior

classification

Peripheral method transaction

  • The peripheral method throws an exception, and in both cases the transaction is rolled back

    • NESTED
    • REQUIRED
  • REQUIRED joins the enclosing method transaction, so it belongs to the same transaction as the enclosing method transaction and will be rolled back once the REQUIRED transaction throws an exception. NESTED is a subtransaction of a peripheral method and has a separate savepoint. Therefore, an exception thrown by a NESTED method is rolled back and does not affect the transactions of the peripheral method.
  • Internal method transaction

    • The inner method transaction is rolled back without affecting the outer method transaction

      • NESTED
      • REQUIRES_NEW
    • NESTED is a NESTED transaction, so after the rollback of the peripheral method, the child transactions of the peripheral method transaction will also be rolled back. REQUIRES_NEW is implemented by starting a new transaction. The internal and peripheral transactions are two transactions, and the rollback of the peripheral transaction does not affect the internal transaction

Second, transaction error use exception scenario

The following error is reported when a statement with a transaction is executed.

org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
Copy the code

The code is as follows:

Analysis of the

MethodA and methodB share the same transaction, methodB marks the transaction as rollback, methodA commits the transaction, and methodA indicates that the transaction has been rollback.

The solution

  • MethodA and methodB should not logically belong to the same transaction, propagating methodB to PROPAGATION_REQUIRES_NEW. If methodB is executed, a new transaction will be created, and no transactions in methodA will be affected
  • Business A and business B should belong to the same transaction logically, so remove the try catch in methodA
  • MethodB does not affect the transaction commit if methodB fails or not. Change methodB’s transaction propagation feature to PROPAGATION_NESTED, that is, methodB does not affect external transactions.