About Hebert Coelho

Senior Java Development, with 4 certifications and a published book about JSF (portuguese only). Founder of the blog uaiHebert.com visited from more than 170 different countries.

Four solutions to the LazyInitializationException – Part 1

In the post today we will talk about the common LazyInitializationException error. We will see four ways to avoid this error, the advantage and disadvantage of each approach and in the end of this post, we will talk about how the EclipseLink handles this exception.

To see the LazyInitializationException error and to handle it, we will use an application JSF 2 with EJB 3.

Topics of the post:

  • Understanding the problem, Why does LazyInitializationException happen?
  • Load collection by annotation
  • Load collection by Open Session in View (Transaction in View)
  • Load collection by Stateful EJB with PersistenceContextType.EXTENDED
  • Load collection by Join Query
  • EclipseLink and lazy collection initialization

At the end of this post you will find the source code to download.

Attention: In this post we will find an easy code to read that does not apply design patterns. This post focus is to show solutions to the LazyInitializationException.

The solutions that you will find here works for web technology like JSP with Struts, JSP with VRaptor, JSP with Servlet, JSF with anything else.

Model Classes

In the post today we will use the class Person and Dog:

package com.model;

import javax.persistence.*;

@Entity
public class Dog {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private int id;

 private String name;

 public Dog() {

 }

 public Dog(String name) {
  this.name = name;
 }

 //get and set
}
package com.model;

import java.util.*;

import javax.persistence.*;

@Entity
public class Person {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private int id;

 private String name;

 @OneToMany
 @JoinTable(name = 'person_has_lazy_dogs')
 private List<Dog> lazyDogs;

 public Person() {

 }

 public Person(String name) {
  this.name = name;
 }

 // get and set
}

Notice that with this two classes we will be able to create the LazyInitializationException. We have a class Person with a Dog list.

We also will use a class to handle the database actions (EJB DAO) and a ManagedBean to help us to create the error and to handle it:

package com.ejb;

import java.util.List;

import javax.ejb.*;
import javax.persistence.*;

import com.model.*;

@Stateless
public class SystemDAO {

 @PersistenceContext(unitName = 'LazyPU')
 private EntityManager entityManager;

 private void saveDogs(List<Dog> dogs) {
  for (Dog dog : dogs) {
   entityManager.persist(dog);
  }
 }

 public void savePerson(Person person) {
   saveDogs(person.getLazyDogs());
   saveDogs(person.getEagerDogs());
   entityManager.persist(person);
 }

 // you could use the entityManager.find() method also
 public Person findByName(String name) {
  Query query = entityManager.createQuery('select p from Person p where name = :name');
  query.setParameter('name', name);

  Person result = null;
  try {
   result = (Person) query.getSingleResult();
  } catch (NoResultException e) {
   // no result found
  }

  return result;
 }
}
package com.mb;

import javax.ejb.EJB;
import javax.faces.bean.*;

import com.ejb.SystemDAO;
import com.model.*;

@ManagedBean
@RequestScoped
public class DataMB {

 @EJB
 private SystemDAO systemDAO;

 private Person person;

 public Person getPerson() {
  return systemDAO.findByName('Mark M.');
 }
}

Why does LazyInitializationException happen?

The Person class has a Dog list. The easier and fattest way to display a person data would be, to use the entityManager.find() method and iterate over the collection in the page (xhtml).

All that we want was that the code bellow would do this…

 // you could use the entityManager.find() method also
 public Person findByName(String name) {
  Query query = entityManager.createQuery('select p from Person p where name = :name');
  query.setParameter('name', name);

  Person result = null;
  try {
   result = (Person) query.getSingleResult();
  } catch (NoResultException e) {
   // no result found
  }

  return result;
 }
 public Person getPerson() {
  return systemDAO.findByName('Mark M.');
 }
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'
 xmlns:f='http://java.sun.com/jsf/core'
 xmlns:h='http://java.sun.com/jsf/html'
 xmlns:ui='http://java.sun.com/jsf/facelets'>
<h:head>

</h:head>
<h:body>
 <h:form>
  <h:dataTable var='dog' value='#{dataMB.personByQuery.lazyDogs}'>
   <h:column>
    <f:facet name='header'>
     Dog name
    </f:facet>
    #{dog.name}
   </h:column>
  </h:dataTable>
 </h:form>
</h:body>
</html>

Notice that in the code above, all we want to do is to find a person in the database and display its dogs to an user. If you try to access the page with the code above you will see the exception bellow:

[javax.enterprise.resource.webcontainer.jsf.application] (http–127.0.0.1-8080-2) Error Rendering View[/getLazyException.xhtml]: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.model.Person.lazyDogs, no session or session was closed                  


at org.hibernate.collection.internal.AbstractPersistentCollection.
throwLazyInitializationException(AbstractPersistentCollection.java:393) 
[hibernate-core-4.0.1.Final.jar:4.0.1.Final]


at org.hibernate.collection.internal.AbstractPersistentCollection.
throwLazyInitializationExceptionIfNotConnected
(AbstractPersistentCollection.java:385) [
hibernate-core-4.0.1.Final.jar:4.0.1.Final]



at org.hibernate.collection.internal.AbstractPersistentCollection.
readSize(AbstractPersistentCollection.java:125) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

To understand better this error let us see how the JPA/Hibernate handles the relationship.

Every time we do a query in the database the JPA will bring to all information of that class. The exception to this rule is when we talk about list (collection). Image that we have an announcement object with a list of 70,000 of emails that will receive this announcement. If you want just to display the announcement name to the user in the screen, imagine the work that the JPA would have if the 70,000 emails were loaded with the name.

The JPA created a technology named Lazy Loading to the classes attributes. We could define Lazy Loading by: “the desired information will be loaded (from database) only when it is needed”.

Notice in the above code, that the database query will return a Person object. When you access the lazyDogs collection, the container will notice that the lazyDogs collection is a lazy attribute and it will “ask” the JPA to load this collection from the database.

In the moment of the query (that will bring the lazyDogs collection) execution, an exception will happen. When the JPA/Hibernate tries to access the database to get this lazy information, the JPA will notice that there is no opened collection. That is why the exception happens, the lack of an opened database connection.

Every relationship that finishes with @Many will be lazy loaded by default: @OneToMany and @ManyToMany. Every relationship that finishes with @One will be eagerly loaded by default: @ManyToOne and @OneToOne. If you want to set a basic field (E.g. String name) with lazy loading just do: @Basic(fetch=FetchType.LAZY).

Every basic field (E.g. String, int, double) that we can find inside a class will be eagerly loaded if the developer do not set it as lazy.

A curious subject about default values is that you may find each JPA implementation (EclipseLink, Hibernate, OpenJPA) with a different behavior for the same annotation. We will talk about this later on.

Load collection by annotation

The easier and the fattest way to bring a lazy list when the object is loaded is by annotation. But this will not be the best approach always.

In the code bellow we will se how to eagerly load a collection by annotation:

@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = 'person_has_eager_dogs')
private List<Dog> eagerDogs;
<h:dataTable var='dog' value='#{dataMB.person.eagerDogs}'>
 <h:column>
  <f:facet name='header'>
   Dog name
  </f:facet>
  #{dog.name}
 </h:column>
</h:dataTable>

Pros and Cons of this approach:

Pros

Cons

Easy to set up

If the class has several collections this will not be good to the server performance

The list will always come with the loaded object

If you want to display only a basic class attribute like name or age, all collections configured as EAGER will be loaded with the name and the age

This approach will be a good alternative if the EAGER collection have only a few items. If the Person will only have 2, 3 dogs your system will be able to handle it very easily. If later the Persons dogs collection starts do grow a lot, it will not be good to the server performance.

This approach can be applied to JSE and JEE.

Load collection by Open Session in View (Transaction in View)

Open Session in View (or Transaction in View) is a design pattern that you will leave a database connection opened until the end of the user request. When the application access a lazy collection the Hibernate/JPA will do a database query without a problem, no exception will be threw.

This design pattern, when applied to web applications, uses a class that implements a Filter, this class will receive all the user requests. This design pattern is very easy to apply and there is two basic actions: open the database connection and close the database connection.

You will need to edit the “web.xml” and add the filter configurations. Check bellow how our code will look like:

 <filter>
  <filter-name>ConnectionFilter</filter-name>
  <filter-class>com.filter.ConnectionFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>ConnectionFilter</filter-name>
  <url-pattern>/faces/*</url-pattern>
 </filter-mapping>
package com.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.transaction.UserTransaction;

public class ConnectionFilter implements Filter {

 @Override
 public void destroy() {

 }

 @Resource
 private UserTransaction utx;

 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  try {
   utx.begin();
   chain.doFilter(request, response);
   utx.commit();
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 @Override
 public void init(FilterConfig arg0) throws ServletException {

 }
}
<h:dataTable var='dog' value='#{dataMB.person.lazyDogs}'>
 <h:column>
  <f:facet name='header'>
   Dog name
  </f:facet>
  #{dog.name}
 </h:column>
</h:dataTable>

Pros and Cons of this approach:

Pros

Cons

The model classes will not need to be edited

All transaction must be handled in the filter class

The developer must be very cautious with database transaction errors. A success message can be sent by the ManagedBean/Servlet, but when the database commits the transacion an error may happen

N+1 effect may happen (more detail bellow)

The major issue of this approach is the N+1 effect. When the method returns a person to the user page, the page will iterate over the dogs collection. When the page access the lazy collection a new database query will be fired to bring the dog lazy list. Imagine if the Dog has a collection of dogs, the dogs children. To load the dogs children list other database query would be fired. But if the children has other children, again the JPA would fire a new database query… and there it goes…

This is the major issue of this approach. A query can create almost a infinity number of other queries.

This approach can be applied to JSE and JEE.

Continue to the second part of this tutorial.

Reference: Four solutions to the LazyInitializationException from our JCG partner Hebert Coelho at the uaiHebert blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

5 Responses to "Four solutions to the LazyInitializationException – Part 1"

  1. Thanks for the article, it is really nice.

  2. Carlos Chau says:

    Very clearly explained! Thank you so much for this awesome article!

  3. Daisy Guti Miller says:

    I just had this exception and I have already read at least 4 articles on the background, setup of JPA, hibernate and such no one got to the point or actually explained what was going on. This was short, sweet, clear and perfect! Thanks a ton! :D

  4. Falsetta says:

    Muito bom o artigo. NOob :)

  5. Sreehareesh says:

    Cool stuff Hebert, thanks

Leave a Reply


× 6 = forty two



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books