Common Expenses: Lazy Loading

When developing the POJO classes for mapping the database I set the fetch type to LAZY. At first i didn’t pu much interes on it but then when I was actually fetching the data from DB I had to lern it better.

The target was to display all project’s data on a page, my first idea was to simply retrieve the project from db

[java]
(Project)session.get(Project.class, 1)
[/java]

and then display it:

[html]
<h3>${project.name}</h3>
<p>${project.description}</p>
<ul>
<c:forEach var="expense" items="${project.expenses}">
<li>${expense.name}</li>
</c:forEach>
</ul>
[/html]

But this didn’t worked. When an entity is instanciated all its collelctions are defined but the content is not loaded, infact lazy loading means Hibernate would fill the collenctions when them are requested.

If you try to retrieve all project’s expenses into the EJB there are no problems as an Hibernate session is opened. When we are into the view context (JSP in this case) there are no Hibernate sessions opened that’s why the expense collection could not be retrieved.

If the fetch mode is set to EAGER Hibernate load all entities collection whe the entity itself is istanciated. The view above would display all the data correctly but if we add a new expense it won’t be added to the collection as the main entity has already benn loaded.

The best solution would be create a Filter which open and close an Hibernate session at view context to lazy load the collections whenever are needed but seems like this way-around exists only in Spring Framework.

The fixeed this problem with in a ‘dirty’ way building a emporary container which collect the projects data every time the page is requested. This is not as performant as lazy loading because it fetches all the data at each request. But it finally make the view display all data.

Leave a Reply

Your email address will not be published. Required fields are marked *