JPA Method
in jakarta.persistence.EntityManagerFactory

R callInTransaction(
  Function<EntityManager,R> work
)


Create a new application-managed EntityManager with an active transaction, and call the given function, passing the EntityManager to the function.

If the transaction type of the persistence unit is JTA, and there is a JTA transaction already associated with the caller, then the EntityManager is associated with this current transaction. If the given function returns without throwing an exception, the result of the function is returned. If the given function throws an exception, the JTA transaction is marked for rollback, and the exception is rethrown.

Otherwise, if the transaction type of the persistence unit is resource-local, or if there is no JTA transaction already associated with the caller, then the EntityManager is associated with a new transaction. If the given function returns without throwing an exception, this transaction is committed and the result of the function is returned. If the function does throw an exception, the transaction is rolled back, and the exception is rethrown.

Finally, the EntityManager is closed before this method returns control to the client.

Parameters:
work - a function to be called in the scope of the transaction
Return:
the value returned by the given function
Since:
JPA 3.2