title: JSF / EJB3 avoiding lazy initialization exceptions in the view layer
body: <p>I have the following JSF/PrimeFaces EJB architecture:</p>
  
  <p>[JSF/PrimeFaces xhtml view] --> [@ManagedBean JSF bean] --> [@Stateless EJB3 bean] --JPA--> [DB]</p>
  
  <p>That is, the JSF views display entities and collections they access on their backing beans (<strong>@ManagedBean</strong>) and these collections and entities are in turn fetched by calling stateless <strong>EJB3</strong> "facade" beans that have the <strong>EntityManager</strong> injected and access the database using <strong>JPA</strong> backed by <strong>Hibernate</strong>. The stateless <strong>EJB3</strong> beans also provide some services but for the most part their role is to provide the Entity objects (<strong>JPA</strong>-annotated) from the database, as requested by the <strong>xhtml</strong> views that need to display them.</p>
  
  <p>Now here's the thing: if my understanding is correct, the moment the Entity beans are returned by the stateless EJB3 beans, they become detached as each <strong>EJB3</strong> bean method demarcates a transaction. It is then often the case that as the <strong>xhtml</strong> views and the <strong>JSF Managed</strong> beans navigate the graphs of the Entity objects so fetched (One-To-Many collections and such), I often get Lazy Initialization exceptions like the following:</p>
  
  <pre><code>javax.el.ELException: ... org.hibernate.LazyInitializationException: failed
  to lazily initialize a collection of role: ..., no session or session was closed
  </code></pre>
  
  <p>The only thing that works is changing collections to be <strong>EAGER</strong> -ly loaded but that's not a pragmatic solution. What are some good patterns to use when detached JPA entity find their way to the view layer in order to avoid once and for all the lazy initialization exceptions rather than having to treat each case in an ad-hoc manner?</p>