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:
03 |
import javax.persistence.*; |
09 |
@GeneratedValue (strategy = GenerationType.AUTO) |
18 |
public Dog(String name) { |
05 |
import javax.persistence.*; |
11 |
@GeneratedValue (strategy = GenerationType.AUTO) |
17 |
@JoinTable (name = 'person_has_lazy_dogs' ) |
18 |
private List lazyDogs; |
24 |
public Person(String name) { |
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:
03 |
import java.util.List; |
06 |
import javax.persistence.*; |
11 |
public class SystemDAO { |
13 |
@PersistenceContext (unitName = 'LazyPU' ) |
14 |
private EntityManager entityManager; |
16 |
private void saveDogs(List dogs) { |
17 |
for (Dog dog : dogs) { |
18 |
entityManager.persist(dog); |
22 |
public void savePerson(Person person) { |
23 |
saveDogs(person.getLazyDogs()); |
24 |
saveDogs(person.getEagerDogs()); |
25 |
entityManager.persist(person); |
29 |
public Person findByName(String name) { |
30 |
Query query = entityManager.createQuery( 'select p from Person p where name = :name' ); |
31 |
query.setParameter( 'name' , name); |
35 |
result = (Person) query.getSingleResult(); |
36 |
} catch (NoResultException e) { |
04 |
import javax.faces.bean.*; |
06 |
import com.ejb.SystemDAO; |
14 |
private SystemDAO systemDAO; |
16 |
private Person person; |
18 |
public Person getPerson() { |
19 |
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…
02 |
public Person findByName(String name) { |
03 |
Query query = entityManager.createQuery( 'select p from Person p where name = :name' ); |
04 |
query.setParameter( 'name' , name); |
08 |
result = (Person) query.getSingleResult(); |
09 |
} catch (NoResultException e) { |
1 |
public Person getPerson() { |
2 |
return systemDAO.findByName( 'Mark M.' ); |
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' > |
12 |
'dog' value= '#{dataMB.personByQuery.lazyDogs}' >
|
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 |
04 |
at org.hibernate.collection.internal.AbstractPersistentCollection. |
05 |
throwLazyInitializationException(AbstractPersistentCollection.java: 393 ) |
06 |
[hibernate-core- 4.0 . 1 .Final.jar: 4.0 . 1 .Final] |
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] |
16 |
at org.hibernate.collection.internal.AbstractPersistentCollection. |
17 |
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:
1 |
@OneToMany (fetch = FetchType.EAGER) |
2 |
@JoinTable (name = 'person_has_eager_dogs' ) |
3 |
private List eagerDogs; |
1 |
'dog' value= '#{dataMB.person.eagerDogs}' >
|
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:
2 |
< filter-name >ConnectionFilter filter-name > |
3 |
< filter-class >com.filter.ConnectionFilter filter-class > |
6 |
< filter-name >ConnectionFilter filter-name > |
7 |
< url-pattern >/faces/* url-pattern > |
03 |
import java.io.IOException; |
05 |
import javax.annotation.Resource; |
06 |
import javax.servlet.*; |
07 |
import javax.transaction.UserTransaction; |
09 |
public class ConnectionFilter implements Filter { |
12 |
public void destroy() { |
17 |
private UserTransaction utx; |
20 |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { |
23 |
chain.doFilter(request, response); |
25 |
} catch (Exception e) { |
32 |
public void init(FilterConfig arg0) throws ServletException { |
1 |
'dog' value= '#{dataMB.person.lazyDogs}' >
|
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:
03 |
import javax.ejb.Stateful; |
04 |
import javax.persistence.*; |
06 |
import com.model.Person; |
09 |
public class SystemDAOStateful { |
10 |
@PersistenceContext (unitName = 'LazyPU' , type=PersistenceContextType.EXTENDED) |
11 |
private EntityManager entityManager; |
13 |
public Person findByName(String name) { |
14 |
Query query = entityManager.createQuery( 'select p from Person p where name = :name' ); |
15 |
query.setParameter( 'name' , name); |
19 |
result = (Person) query.getSingleResult(); |
20 |
} catch (NoResultException e) { |