Hibernate “Transaction already active” behaviour with custom transaction manager

Description

While migrating from Hibernate 4.x to latest Hibernate 5 version, I'm encountering an issue with regards to transaction management.

In our code (actually a unit test), there is a transaction manager that begins a JTA transaction, followed by a sequence of multiple invocations of a method that call to creates a Session to do a save (in which a beginTransaction() is done). Below is an example that reproduces the issue (the scenario is not using Spring or any other container managed transaction management):

This is causing an IllegalStateException to be thrown with the message "Transaction already active". This behavior seems to have been introduced in Hibernate 5.2.0 (this is the commit) to comply with JPA's EntityTransaction. Previously, Hibernate just ignored the beginning the physical transaction itself because it knows an enclosing transaction is present: it just creates a wrapper JtaTransaction with isInitiator set to false.

This exception is thrown in org.hibernate.engine.transaction.internal.TransactionImpl, specifically the begin() method:

This contradicts with the user manual, where it says the below:

Is there a way to restore the old behavior? Our code relies on such a custom TM scenario. It would be great to have your feedback on this.

Attachments

4

Activity

Show:

Gavin KingNovember 20, 2024 at 10:29 PM

The fix to this issue didn’t really go far enough, IMO. The beginTransaction() method is not defined by JPA, and JPA compliance doesn’t apply to it. On the other hand, its own Javadoc clearly states that you can safely call it when there is already an active transaction:

Begin a unit of work and return the associated Transaction object. If a new underlying transaction is required, begin the transaction. Otherwise, continue the new work in the context of the existing underlying transaction.

So either that javadoc must change, or we must make the implementation agree with the doc. I lean toward the second option.

Former userFebruary 19, 2019 at 6:11 AM

Fixed in 5.3 branch as well.

Mahmoud AnoutiNovember 19, 2018 at 3:36 PM

Any chance this can be backported to 5.3?

Former userNovember 15, 2018 at 8:46 PM

Yes, I think this should be backported.

Andrea BorieroNovember 15, 2018 at 3:03 PM

Hi ,

you are welcome.

Today will release the 5.4.0.CR1.

Fixed

Details

Assignee

Reporter

Components

Fix versions

Affects versions

Priority

Created November 2, 2018 at 8:58 PM
Updated November 20, 2024 at 10:34 PM
Resolved February 19, 2019 at 6:11 AM