Four solutions to the LazyInitializationException

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.

4 thoughts on “Four solutions to the LazyInitializationException

  1. 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.

  2. Such a mess… Hibernate shoudn’t have been included into JEE (as a JPA). Now we have an umrella specification where every rule is just a hint, and “is not required to be implemented”.

    • Hello asd,

      I believe that everything is about a trade of. If you chose JPA you will have access to several advantages, but you will need to follow its rules.

      I do not see it as a problematic JEE component, if you do not want it you are free to use any other persistence frameworks.

      Thanks for passing by

Leave a Comment