Four solutions to the LazyInitializationException

阅读更多

from http://www.javacodegeeks.com/2012/07/four-solutions-to-lazyinitializationexc_05.html

http://www.javacodegeeks.com/2012/07/four-solutions-to-lazyinitializationexc.html

 

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:

01 package com.model;
02  
03 import javax.persistence.*;
04  
05 @Entity
06 public class Dog {
07  
08  @Id
09  @GeneratedValue(strategy = GenerationType.AUTO)
10  private int id;
11  
12  private String name;
13  
14  public Dog() {
15  
16  }
17  
18  public Dog(String name) {
19   this.name = name;
20  }
21  
22  //get and set
23 }
01 package com.model;
02  
03 import java.util.*;
04  
05 import javax.persistence.*;
06  
07 @Entity
08 public class Person {
09  
10  @Id
11  @GeneratedValue(strategy = GenerationType.AUTO)
12  private int id;
13  
14  private String name;
15  
16  @OneToMany
17  @JoinTable(name = 'person_has_lazy_dogs')
18  private List lazyDogs;
19  
20  public Person() {
21  
22  }
23  
24  public Person(String name) {
25   this.name = name;
26  }
27  
28  // get and set
29 }

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:

01 package com.ejb;
02  
03 import java.util.List;
04  
05 import javax.ejb.*;
06 import javax.persistence.*;
07  
08 import com.model.*;
09  
10 @Stateless
11 public class SystemDAO {
12  
13  @PersistenceContext(unitName = 'LazyPU')
14  private EntityManager entityManager;
15  
16  private void saveDogs(List dogs) {
17   for (Dog dog : dogs) {
18    entityManager.persist(dog);
19   }
20  }
21  
22  public void savePerson(Person person) {
23    saveDogs(person.getLazyDogs());
24    saveDogs(person.getEagerDogs());
25    entityManager.persist(person);
26  }
27  
28  // you could use the entityManager.find() method also
29  public Person findByName(String name) {
30   Query query = entityManager.createQuery('select p from Person p where name = :name');
31   query.setParameter('name', name);
32  
33   Person result = null;
34   try {
35    result = (Person) query.getSingleResult();
36   catch (NoResultException e) {
37    // no result found
38   }
39  
40   return result;
41  }
42 }
01 package com.mb;
02  
03 import javax.ejb.EJB;
04 import javax.faces.bean.*;
05  
06 import com.ejb.SystemDAO;
07 import com.model.*;
08  
09 @ManagedBean
10 @RequestScoped
11 public class DataMB {
12  
13  @EJB
14  private SystemDAO systemDAO;
15  
16  private Person person;
17  
18  public Person getPerson() {
19   return systemDAO.findByName('Mark M.');
20  }
21 }

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…

01  // you could use the entityManager.find() method also
02  public Person findByName(String name) {
03   Query query = entityManager.createQuery('select p from Person p where name = :name');
04   query.setParameter('name', name);
05  
06   Person result = null;
07   try {
08    result = (Person) query.getSingleResult();
09   catch (NoResultException e) {
10    // no result found
11   }
12  
13   return result;
14  }
1  public Person getPerson() {
2   return systemDAO.findByName('Mark M.');
3  }
01 '-//W3C//DTD XHTML 1.0 Transitional//EN'
02   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
03 'http://www.w3.org/1999/xhtml'
04  xmlns:f='http://java.sun.com/jsf/core'
05  xmlns:h='http://java.sun.com/jsf/html'
06  xmlns:ui='http://java.sun.com/jsf/facelets'>
07
08  
09
10
11  
12   'dog' value='#{dataMB.personByQuery.lazyDogs}'>
13    
14     'header'>
15      Dog name
16     
17     #{dog.name}
18    
19   
20  
21
22

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:

01 [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                 
02  
03  
04 at org.hibernate.collection.internal.AbstractPersistentCollection.
05 throwLazyInitializationException(AbstractPersistentCollection.java:393)
06 [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
07  
08  
09 at org.hibernate.collection.internal.AbstractPersistentCollection.
10 throwLazyInitializationExceptionIfNotConnected
11 (AbstractPersistentCollection.java:385) [
12 hibernate-core-4.0.1.Final.jar:4.0.1.Final]
13  
14  
15  
16 at org.hibernate.collection.internal.AbstractPersistentCollection.
17 readSize(AbstractPersistentCollection.java:125) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
18

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:

1 @OneToMany(fetch = FetchType.EAGER)
2 @JoinTable(name = 'person_has_eager_dogs')
3 private List eagerDogs;
1 'dog' value='#{dataMB.person.eagerDogs}'>
2  
3   'header'>
4    Dog name
5   
6   #{dog.name}
7  
8

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:

1 <b> <filter>
2   <filter-name>ConnectionFilterfilter-name>
3   <filter-class>com.filter.ConnectionFilterfilter-class>
4  filter>
5  <filter-mapping>
6   <filter-name>ConnectionFilterfilter-name>
7   <url-pattern>/faces/*url-pattern>
8  filter-mapping>b>
01 package com.filter;
02  
03 import java.io.IOException;
04  
05 import javax.annotation.Resource;
06 import javax.servlet.*;
07 import javax.transaction.UserTransaction;
08  
09 public class ConnectionFilter implements Filter {
10  
11  @Override
12  public void destroy() {
13  
14  }
15  
16  @Resource
17  private UserTransaction utx;
18  
19  @Override
20  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throwsIOException, ServletException {
21   try {
22    utx.begin();
23    chain.doFilter(request, response);
24    utx.commit();
25   catch (Exception e) {
26    e.printStackTrace();
27   }
28  
29  }
30  
31  @Override
32  public void init(FilterConfig arg0) throws ServletException {
33  
34  }
35 }
1 'dog' value='#{dataMB.person.lazyDogs}'>
2  
3   'header'>
4    Dog name
5   
6   #{dog.name}
7  
8

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.

 

Load collection by Stateful EJB with PersistenceContextType.EXTENDED

This approach can be applied only to applications that works with Full JEE environments: to use a EJB with PersistenceContextType.EXTENDED.

Check the code below how the DAO would look like:

01 package com.ejb;
02  
03 import javax.ejb.Stateful;
04 import javax.persistence.*;
05  
06 import com.model.Person;
07  
08 @Stateful
09 public class SystemDAOStateful {
10  @PersistenceContext(unitName = 'LazyPU', type=PersistenceContextType.EXTENDED)
11  private EntityManager entityManager;
12  
13  public Person findByName(String name) {
14   Query query = entityManager.createQuery('select p from Person p where name = :name');
15   query.setParameter('name', name);
16  
17   Person result = null;
18   try {
19    result = (Person) query.getSingleResult();
20   catch (NoResultException e) {
21    // no result found

你可能感兴趣的:(Four solutions to the LazyInitializationException)