lazyinitializationexception when session is not cl

2019-09-07 16:05发布

问题:

I am using Hibernate in my object and getting lazyinitializationexception even when session is not closed.

Here is the relation of the objects in issue. There are 3 Objects:

  1. ObjectA
  2. ObjectB
  3. ObjectC

ObjectA includes ObjectB as FetchType=EAGER ObjectB includes ObjectC as FetchType=LAZY

We are fetching ObjectA. So, because of eager fetch type, it is automatically fetching ObjectB. But when I am trying to fetch ObjectC using ObjectB, it is giving this error.

The code is too big and proprietary. So, can't share the code.

Note: 1. All these operations are being done inside one transaction only. 2. I checked the logs and found out that session is not being closed. 3. I found similar link - LazyInitializationException in JPA and Hibernate I am using annotationDriven tag also in my code as suggested in this link.

I am not getting if why is it happening.

回答1:

is my understanding is correct?

ObjectA includes ObjectB as FetchType=EAGER ObjectB includes ObjectC as FetchType=LAZY

We are fetching ObjectA. So, because of eager fetch type, it is automatically fetching ObjectB. But when I am trying to fetch ObjectC using ObjectB, it is giving this error.

ObjectA.getObjectB = OK ? i mean no exception thrown or no error right?

then when you access ObjectC by ObjectB by :

  1. ObjectB.getObjectC or
  2. ObjectA.getObjectB.getObjectC ?

and you get an exception of LazyInitializationException.

Hibernate Documentation says that..

A LazyInitializationException will be thrown by Hibernate if an uninitialized collection or proxy is accessed outside of the scope of the Session, i.e., when the entity owning the collection or having the reference to the proxy is in the detached state.

Sometimes a proxy or collection needs to be initialized before closing the Session. You can force initialization by calling cat.getSex() or cat.getKittens().size(), for example. However, this can be confusing to readers of the code and it is not convenient for generic code.

The static methods Hibernate.initialize() and Hibernate.isInitialized(), provide the application with a convenient way of working with lazily initialized collections or proxies. Hibernate.initialize(cat) will force the initialization of a proxy, cat, as long as its Session is still open. Hibernate.initialize( cat.getKittens() ) has a similar effect for the collection of kittens.

from - https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/performance.html#performance-fetching-initialization

You have two option

Change FetchType=LAZY to FetchType=EAGER on your relationship between ObjectB and ObjectC

or use Hibernate.initialize(ObjectC); to initialize the objectC before the transaction ends..

hope this will help you..