Session is not unset for PersistentBag loaded in temp session.

Description

I noticed the issue in our system when trying to migrate to the latest version. In some scenarios, we start to receive

1 Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed

.

I looked into the issue and found that the behavior changed in version 5.2.2 and related to the fix created for issue - Session not flushing starting from 5.2.0 in Karaf + Arie and particularly in the commit https://github.com/hibernate/hibernate-orm/commit/109410b153f8e15ab3de3e99cb9924a085fe3a0f SessionImpl.java

The lazy loading is broken for the following scenario. Suppose we have 2 classes
class A {
// lazy loaded
List<B> itemsB;
}
class B {
// lazy loaded
List<C> itemsC;
}
In our application we using extended persistent context and set "hibernate.enable_lazy_load_no_trans" flag to true;

In request 1 we load an instance of class A and save the reference to the loaded instance in the memory. The instance of class A has itemsB lazy initialized.
In request 2 we trying to access itemsB property from the instance A loaded in the first request. As the session where A was loaded already closed (and set to null) Hibernate creates a temp session to load itemsB.Once they loaded the temp session is closed by hibernate. Afterwards, in the same request, we trying to iterate over itemsC for instance of B. The ItemsC is lazy loaded collection and it has a link to the session and because the session used to load itemsB already closed we have the exception.

Previously, for all session, before the session is closed it will be removed from all lazyloaded collections so the collection then could be loaded with a new session. However, as part of changes in SessionImpl.class this is not true anymore. When session closing while the transaction is active, or in my case for temp session the session is not unset for lazy loaded collections.

1 2 3 4 5 6 7 8 9 10 11 if ( discardOnClose || !isTransactionInProgress() ) { + super.close(); + } + else { + //Otherwise, session auto-close will be enabled by shouldAutoCloseSession(). + waitingForAutoClose = true; + closed = true; + } // previous code // super.close();

Environment

JPA/JTA EXTENDED, UNSYNCHRONIZED persistent context
hibernate.enable_lazy_load_no_trans=true;

Status

Assignee

Andrea Boriero

Reporter

Mikhail Chibel

Fix versions

None

Labels

None

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Worked in

5.2.1

Components

Affects versions

5.2.2
5.2.12

Priority

Critical
Configure