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<Dog> 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<Dog> 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 |
<b> public Person getPerson() {
|
2 |
return systemDAO.findByName( 'Mark M.' );
|
01 |
<b><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
|
12 |
<h:dataTable var= 'dog' value= '#{dataMB.personByQuery.lazyDogs}' >
|
14 |
<f:facet name= 'header' >
|
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 |
<b>[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 |
<b> @OneToMany (fetch = FetchType.EAGER)
|
2 |
@JoinTable (name = 'person_has_eager_dogs' )
|
3 |
private List<Dog> eagerDogs;</b>
|
1 |
<b><h:dataTable var= 'dog' value= '#{dataMB.person.eagerDogs}' >
|
3 |
<f:facet name= 'header' >
|
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 >
|
01 |
<b> package com.filter;
|
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 |
<b><h:dataTable var= 'dog' value= '#{dataMB.person.lazyDogs}' >
|
3 |
<f:facet name= 'header' >
|
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) {
|
01 |
<b> public class DataMB {
|
05 |
private SystemDAOStateful daoStateful;
|
07 |
public Person getPersonByStatefulEJB() {
|
08 |
return daoStateful.findByName( 'Mark M.' );
|
1 |
<b><h:dataTable var= 'dog' value= '#{dataMB.personByStatefulEJB.lazyDogs}' >
|
3 |
<f:facet name= 'header' >
|
Pros and Cons of this approach:
Pros
|
Cons
|
The container will control the database transaction
|
Works only for JEE
|
The model classes will not need to be edited
|
N+1 effect may happen
|
|
A great amount of Stateful EJBs may affect the container memory.
|
This approach may create the N+1 effect and the Stateful EJB has a characteristic of not being removed/destroyed while the its session is not expired or until it lost its reference.
Warning: It is not a good practice to hold a reference to an injected EJB in objects that remain in a Pool. The JSF will create a ManagedBean pool to handle better the user requests; when it is necessary the container will increase or decrease the number of ManagedBeans in the pool. In the code of this post imagine if the container create 100 instances of ManagedBeans in the pool, the server will hold 100 Stateful EJBs in memory. The solution to this problem would be a JNDI LookUp to the Stateful EJB.
Load collection by Join Query
This solution is easy to understand and to apply.
See the code below:
01 |
<b> public Person findByNameWithJoinFech(String name) {
|
02 |
Query query = entityManager.createQuery( 'select p from Person p join fetch p.lazyDogs where p.name = :name' );
|
03 |
query.setParameter( 'name' , name);
|
07 |
result = (Person) query.getSingleResult();
|
08 |
} catch (NoResultException e) {
|
1 |
<b> public Person getPersonByQuery() {
|
2 |
return systemDAO.findByNameWithJoinFech( 'Mark M.' );
|
1 |
<b> <h:dataTable var= 'dog' value= '#{dataMB.personByQuery.lazyDogs}' >
|
3 |
<f:facet name= 'header' >
|
Pros and Cons of this approach:
Pros
|
Cons
|
Just one query will be fired in the database
|
It would be necessary one query for each accessed collection/lazy attribute
|
The model classes will not need to be edited
|
|
Will bring only the desired data
|
|
The N+1 effect will not happen
|
|
This approach has the disadvantage of the need of a new query to access each model class collection/lazy attribute. If we need to query only the Person dogs we would need of a specific query. Imagine that we would need to query for the Person emails, it would be necessary a different query.
This approach can be applied to JSE and JEE.
EclipseLink and lazy collection initialization
The relationships default values are:
Relationship
|
Fetch
|
@OneToOne
|
EAGER
|
@OneToMany
|
LAZY
|
@ManyToOne
|
EAGER
|
@ManyToMany
|
LAZY
|
But the JPA Spec* says that:
The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified. In particular, lazy fetching might only be available for Basic mappings for which property-based access is used.
As you can see in the text above, the JPA implementation may ignore the hint strategy if it wants to. The EclipseLink has a behavior with JEE and other behavior to JSE. You can see each behavior here:http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#What_You_May_Need_to_Know_About_EclipseLink_JPA_Lazy_Loading
We can find in the internet some people saying that even with a lazy collection the EclipseLink does the n+1 queries when the entity is loaded. And we can find this behavior of users with Glassfish and EJB.
Below you will see some tips to use correctly lazy load with EclipseLink:
* JSR-000220 Enterprise JavaBeans 3.0 Final Release (persistence) 9.1.18 and will repeat to the otters JPA relationships.
The end!
In my opinion the best solution is the Join Fetch Query. It is up to you to choose the best solution to your application.
Click here to download the source code of this post. If you want to run the code of this post you will need to create a database named LazyExceptionDB and the JBoss module. Attached to the source code is the Postgres module. If you want to see how to set up the datasource and the Postgres or MySQL module you can see it here: Full WebApplication JSF EJB JPA JAAS.
I hope this post might help you.
If you have any comment or doubt just post it.
See you soon.
相关推荐
Simply make a copy of the relevant page of the book, mark the error, and send it to: Book Editor, PMI Publications, Four Campus Boulevard, Newtown Square, PA 19073-3299 USA, or e-mail: booked@pmi.org...
标题中的"four_four_TheFour_"似乎是一种命名约定或者代码标识,它可能代表一个项目、模块或者版本号。"four of the five pieces"的描述暗示这里有五个部分或组件,而我们关注的是其中的四个。结合标签"four TheFour...
concerned with the housing of the electronics (from component housing to PCB to enclosure and finally to the rack) as well as the ability of this housing to maintain its integrity under various ...
Four different tricks to bypass StackShield and StackGuard protection Four different tricks to bypass StackShield and StackGuard protection Four different tricks to bypass StackShield and StackGuard ...
This is followed by four projects that you can implement to learn how to build MicroPython IOT solutions. Throughout the book are examples of how to implement many of the concepts presented. The ...
Four_solutions_with_heuristic_algorithm_about_Trav_TSPSolutions
He is the founder of the WorldWide WarDrive, a four-year project to assess the security posture of wireless networks deployed throughout the world. Chris was also the original organizer of the DEF ...
Amazon, Apple, Facebook, and Google are the four most influential companies on the planet. Just about everyone thinks they know how they got there. Just about everyone is wrong. For all that's been ...
Building.Solutions.with.Microsoft.Dot.NET.Compact.Framework,Architecture & Best Practices for Mobile Develop 英文版 "If you've been looking for one book on the .NET Compact Framework that will ...
Gilbert Strang's textbooks have changed the entire approach to learning linear algebra -- away from abstract vector spaces to specific examples of the four fundamental subspaces: the column space and ...
This document contains the solutions to review questions and problems for the 5th edition of Computer Networking: A Top-Down Approach by Jim Kurose and Keith Ross. These solutions are being made ...
theFour.cpp
Finally, we identify four factors that play a crucial role in the variation range of the avail-bw: traffic load, number of competing flows, rate of competing flows, and of course the measurement time...
Scientists have marveled at the beauty and elegance of his analysis, while practicing programmers have successfully applied his "cookbook" solutions to their day-to-day problems. All have admired ...
Four alternative approaches to the family/school liaison role FOUR ALTERNATIVE APPROACHES TO THE FAMILY /SCHOOL LIAISON ROLE MICHAEL DAVID LOVEN University of North Carolina at Chapel Hill ...