Java – Rollback all nested transactions when outer one is marked for rollback

javapropagationrollbackspringtransactions

I've got two methods annotated with @Transactional. The second method is called somewhere nested inside the first one.

Now I want the following behaviour to happen:

  • Every time the second, nested method is entered, a new nested
    transaction should be created. When that transaction is marked for a
    rollback, only that transaction should be rolled back.
  • But when the
    transaction of the outer method is marked for a rollback, every
    nested transaction inside — whether it's marked for a rollback or not —
    should be rolled back.

How do I have to set the Propagation values to achieve such functionality?


P. S.: I'm using a HibernateTransactionManager.

Best Answer

You need to use NESTED. Note that this propagation mode uses JDBC SavePoints in order to achieve this behavior, and that the nested behavior thus only works if the transaction is just a wrapper around the JDBC connection. It won't work for JTA transactions. See the Spring documentation for more details.

Related Topic