Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: lazy-loading doesn't work on one-to-many mapping on set

I'm using Spring together with Hibernate for developing a Portlet for the Liferay portal server. I now have basically two entities, A and B, where A possibly contains many B's. So this goes to a one-to-many mapping between the two.

<set cascade="all" lazy="true" name="comments" order-by="creationDate desc">
   <key column="lfpn_pinboardentries_idPinboardEntry" not-null="true"/>
   <one-to-many class="Comment"/>
</set>

In the corresponding DAO of entity A in the DAO layer, I'm inheriting from "HibernateDaoSupport" provided by spring, and so a typical retrieval of data looks like the following:

...
public A getA(long id) {
  return (A) getHibernateTemplate().get(A.class, id);
}
...

Everything works fine if I'm having "lazy=false", but as soon as I'm switching to "lazy=true" it gives me the following error:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.lifepin.entities.PinboardEntry.comments, no session or session was closed

Does anyone have a suggestion what could be the problem or hints how to solve it?

Thanks!

like image 681
Juri Avatar asked Oct 18 '25 19:10

Juri


2 Answers

You usually get this error if you have loaded the object in one request, then without accessing the lazy loaded property, saved the object in session. If you then in a different request try to access the lazy loaded property you will get this exception.

Simply put : the Hibernate session in which the object was initially loaded has closed. On accessing the lazily loaded property of this object in a different Hibernate session causes this exception.

You will have to reload your object into the current Hibernate session to be able lazily load a property

like image 166
Tom Carter Avatar answered Oct 20 '25 10:10

Tom Carter


A good discussion on hibernate lazy loading and a very helpful solution (called Preload pattern) can be found here: http://entwickler-forum.de/showthread.php?t=47067

Unfortunately this is a German website. But at least the source code and its doc is in English.

The core idea of the website above is to give an opportunity to avoid loading the whole object graph (via lazy loading) and to explicitly specify which parts of the object graph should be loaded in a given situation.

like image 20
jens Avatar answered Oct 20 '25 10:10

jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!