Four solutions to the LazyInitializationException


Posted on May 2, 2012 by

Share it now!

Hello, how are you?

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:

  • Page 3: Understanding the problem, Why does LazyInitializationException happen?
  • Page 4: Load collection by annotation
  • Page 5: Load collection by Open Session in View (Transaction in View)
  • Page 6: Load collection by Stateful EJB with PersistenceContextType.EXTENDED
  • Page 7: Load collection by Join Query
  • Page 8: 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.

The only page code that does not apply to JSE (usually Desktop applications) is the Page 6 with EJB.

Response to Four solutions to the LazyInitializationException

  1. James Sutherland

    Note that EclipseLink does not have this issue, and it has nothing to do with EAGER. EclipseLink supports LAZY in JEE and JSE, for JSE you must use either dynamic weaving using an agent, or static weaving.

    The reason EclipseLink does not have this issue is that when you access a LAZY relationship outside of the transaction, or after the EntityManager has been closed, EclipseLink just acquires a new connection from its connection pool to read the related objects.

    The only time you will have this issue with EclipseLink is when you serialize the object, then the LAZY will be dead and you will get an error. In EclipseLink you can use JOIN FETCH, fetch groups, or load groups to resolve the issue.

Leave a Reply

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


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *