To add to @Philippe Marshall's correct answer and your comment - REQUIRES_NEW
will create a new transaction, independent from the first one. They are not nested. The first transaction is suspended while the second is active. Once the second transaction commits, the first one is resumed.
You do not have to setRollbackOnly()
manually. Most PersistenceException
s will do that if needed. You will gain nothing by rolling back transactions that you don't have to. For example, when querying data, you may get a NoResultException
or a NonUniqueResultException
. They do not cause a transaction to be rolled back as there is no risk of inconsistencies between the persistence context and the DB.
You do not need to specify neither @TransactionAttribute(REQUIRED)
nor @TransactionManagement(TransactionManagementType.CONTAINER)
- both are the default settings.
EDIT: to answer your further questions:
I am assuming @TransactionAttribute(REQUIRES_NEW)
on method2
and therefore two separate transactions.
If there is an Exception
that leads to the rollback of the transaction in method2
, the transaction from method1
will not be rolled back if the Exception is caught. If the Exception
is not caught, both transactions will be rolled back.
When setting the rollback flag on a transaction, it does not matter whether it happens before or after DB operations, since the entire transaction is rolled back.
Once method2
returns, it's transaction is committed. Rolling back or committing the transaction from method1
afterwards has no influence on the results of the first transaction.
A general advice - do not catch Throwable
- it is much too broad and you might swallow exceptions which you would rather let propagate to the surface.