I have a domain object that has an attribute which is a collection containing another domain object. This is accomplished using a hibernate mapping (which eventually performs a join on another table). Hibernate, by default, seems to lazily instantiate this collection. This turns out to be a great thing because, depending upon what I need displayed, I do not always need the collection to be loaded.
My issue is the following: when writing my hibernate queries (in my DAOs), I use the following to open / close a Session:
Session session = getSessionFactory().openSession();
//query goes here using the session var
session.close();
The problem is: when Hibernate finally comes around to lazily loading my collection, the Session has long been closed! How can I get around this? I assume that I have to close the session as I am doing…
This is the error I get:
SEVERE: failed to lazily initialize a collection of ...
If this is occurring within a webapp, then the easy fix for this is to use an OpenSessionInViewInterceptor or OpenSessionInViewFilter. These delay the closing of the session until the whole request has completed, allowing you to navigate lazy associations when rendering the view.
A more general solution is to rewrite your queries so that they explicitly specify which associations should be fetched up-front. This lets you keep the associations lazy by default, while at the same time catering for special cases where you want them fetched eagerly. See the description of “fetch joins” in the Hibernate docs.