title: LazyInitializationException with CDI Managed Bean and Stateful Session Bean
body: <p>I have a CDI Managed Bean (a bean annotated with @Named that is used on JSF) that has a Stateful Session Bean injected. This session bean is like a service, it has the entity manager (annotated with @PersistenceContext(type= PersistenceContextType.EXTENDED)) and expose come methods to manipulate some entities. Those entities are on the managed bean, who is ConversationScoped. Then, the JSF calls a method of the managed bean and the managed bean calls some method of the "service" (the stateful session bean).
  I don't know if this is the best design, but it was working well.
  But there's an Entity that have some collections that need to be fetched with LAZY. And the first time I open the page, it appears to work well, but when I try to click any button or do any action, I have the LazyInitializationException.
  Do somebody have any tip? I don't know if there's anything wrong. I put the session bean like stateful and the persistence context extended. This session bean is injected within the managed bean, that has the entities. Why it's throwing this exception? How could the entity manager be closed?</p>
  
  <p>This is the code of the Entity that is in trouble:</p>
  
  <pre><code>@Entity
  public class ParametrosVingentes implements Serializable {
  
      public static final String ID = "settings";
  
      private static final long serialVersionUID = 1L;
  
      @Id
      private String id;
      @OneToOne
      private ValorHora valorHora;
      @OneToMany
      @JoinTable(
              name="BuscaSistecVingentes",
              joinColumns = @JoinColumn( name="parametros_vingentes_fk"),
              inverseJoinColumns = @JoinColumn( name="agendamento_fk")
      )
      private List&lt;AgendamentoBuscaSistec&gt; agendamentosBuscaSistec;
      @OneToMany
      @JoinTable(
              name="ExportacaoZeusVingentes",
              joinColumns = @JoinColumn( name="parametros_vingentes_fk"),
              inverseJoinColumns = @JoinColumn( name="agendamento_fk")
      )
      private List&lt;AgendamentoExportacaoZeus&gt; agendamentosExportacaoZeus;
      @OneToMany
      @JoinTable(
              name="ImportacaoZeusVingentes",
              joinColumns = @JoinColumn( name="parametros_vingentes_fk"),
              inverseJoinColumns = @JoinColumn( name="agendamento_fk")
      )
      private List&lt;AgendamentoImportacaoZeus&gt; agendamentosImportacaoZeus;
  
      public ParametrosVingentes() {
      this.id = ID;
      }
  // getters and setters...
  </code></pre>
  
  <p>This is the Stateful Session Bean:</p>
  
  <pre><code>@Stateful
  @LocalBean
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public class ParametrosService implements Serializable {
  
      @PersistenceContext(type= PersistenceContextType.EXTENDED)
      private EntityManager entityManager;
  
      public void cadastrar(ValorHora valorHora){
          ValorHoraDao valorHoraDao = new ValorHoraDao(entityManager);
          valorHoraDao.salvar(valorHora);
      }
  
      @TransactionAttribute(TransactionAttributeType.SUPPORTS)
          public List&lt;ValorHora&gt; listarValorHora(){
          ValorHoraDao valorHoraDao = new ValorHoraDao(entityManager);
          return valorHoraDao.getAll();
      }
  
      public boolean excluir(ValorHora valorHora){
          if(valorHora.getRemessas() != null &amp;&amp; !valorHora.getRemessas().isEmpty()){
              return false;
          }
          ValorHoraDao valorHoraDao = new ValorHoraDao(entityManager);
          valorHoraDao.remover(valorHora);
          return true;
      }
  
      public void cadastrar(AgendamentoBuscaSistec agendamentoBuscaSistec){
          AgendamentoBuscaSistecDao agendamentoBuscaSistecDao = new AgendamentoBuscaSistecDao(entityManager);
          agendamentoBuscaSistecDao.salvar(agendamentoBuscaSistec);
      }
  
      @TransactionAttribute(TransactionAttributeType.SUPPORTS)
      public List&lt;AgendamentoBuscaSistec&gt; listarAgendamentoBuscaSistec(){
          AgendamentoBuscaSistecDao agendamentoBuscaSistecDao = new AgendamentoBuscaSistecDao(entityManager);
          return agendamentoBuscaSistecDao.getAgendamentos();
      }
  
      public void excluir(AgendamentoBuscaSistec agendamentoBuscaSistec){
          AgendamentoBuscaSistecDao agendamentoBuscaSistecDao = new AgendamentoBuscaSistecDao(entityManager);
          agendamentoBuscaSistecDao.remover(agendamentoBuscaSistec);
      }
  
      public void cadastrar(AgendamentoExportacaoZeus agendamentoExportacaoZeus){
          AgendamentoExportacaoZeusDao agendamentoExportacaoZeusDao = new AgendamentoExportacaoZeusDao(entityManager);
          agendamentoExportacaoZeusDao.salvar(agendamentoExportacaoZeus);
      }
  
      @TransactionAttribute(TransactionAttributeType.SUPPORTS)
          public List&lt;AgendamentoExportacaoZeus&gt; listarAgendamentoExportacaoZeus(){
          AgendamentoExportacaoZeusDao agendamentoExportacaoZeusDao = new AgendamentoExportacaoZeusDao(entityManager);
          return agendamentoExportacaoZeusDao.getAgendamentos();
      }
  
      public void excluir(AgendamentoExportacaoZeus agendamentoExportacaoZeus){
          AgendamentoExportacaoZeusDao agendamentoExportacaoZeusDao = new AgendamentoExportacaoZeusDao(entityManager);
          agendamentoExportacaoZeusDao.remover(agendamentoExportacaoZeus);
      }
  
      public void cadastrar(AgendamentoImportacaoZeus agendamentoImportacaoZeus){
          AgendamentoImportacaoZeusDao agendamentoImportacaoZeusDao = new AgendamentoImportacaoZeusDao(entityManager);
          agendamentoImportacaoZeusDao.salvar(agendamentoImportacaoZeus);
      }
  
      @TransactionAttribute(TransactionAttributeType.SUPPORTS)
      public List&lt;AgendamentoImportacaoZeus&gt; listarAgendamentoImportacaoZeus(){
          AgendamentoImportacaoZeusDao agendamentoImportacaoZeusDao = new AgendamentoImportacaoZeusDao(entityManager);
          return agendamentoImportacaoZeusDao.getAgendamentos();
      }
  
      public void excluir(AgendamentoImportacaoZeus agendamentoImportacaoZeus){
          AgendamentoImportacaoZeusDao agendamentoImportacaoZeusDao = new AgendamentoImportacaoZeusDao(entityManager);
          agendamentoImportacaoZeusDao.remover(agendamentoImportacaoZeus);
      }
  
      @TransactionAttribute(TransactionAttributeType.SUPPORTS)
      public ParametrosVingentes getParametrosVingentes(){
          return ParametrosUtil.getParametrosVingentes(entityManager);
      }
  
      public void atualizarParametrosVingentes(ParametrosVingentes parametrosVingentes){
          ParametrosVingentesDao parametrosVingentesDao = new ParametrosVingentesDao(entityManager);
          parametrosVingentes = parametrosVingentesDao.atualizar(parametrosVingentes);
      }
  
  }
  </code></pre>
  
  <p>The managed bean calls the method getParametrosVingentes() of the session bean. I uses a static method of the ParametrosUtil to get (if it exists) or create (if it doesn't exist) the ParametrosVingentes. It's because it's necessary that there's only one ParametrosVingentes in the application. It's the bean that has the parameters used by other components.
  This is the code of ParametrosUtil:</p>
  
  <pre><code>public class ParametrosUtil {
  
      public static synchronized ParametrosVingentes getParametrosVingentes(EntityManager entityManager){
          ParametrosVingentesDao parametrosVingentesDao = new ParametrosVingentesDao(entityManager);
          ParametrosVingentes parametrosVingentes = parametrosVingentesDao.buscar(ParametrosVingentes.ID);
          if(parametrosVingentes == null){
              parametrosVingentes = new ParametrosVingentes();
          }
          return parametrosVingentes;
      }
  
      public static synchronized ParametrosVingentes atualizarParametrosVingentes(ParametrosVingentes parametrosVingentes, EntityManager entityManager){
          ParametrosVingentesDao parametrosVingentesDao = new ParametrosVingentesDao(entityManager);
          return parametrosVingentesDao.atualizar(parametrosVingentes);
      }
  }
  </code></pre>
  
  <p>This is the managed bean:</p>
  
  <pre><code>@Named(value = "parametros")
  @ConversationScoped
  public class Parametros implements Serializable {
  
      public static final int VISAO_PARAMETROS_VINGENTES = 1;
      public static final int VISAO_VALOR_HORA = 2;
      public static final int VISAO_AGENDAMENTO_SISTEC = 3;
      public static final int VISAO_AGENDAMENTO_EXPORTACAO_ZEUS = 4;
      public static final int VISAO_AGENDAMENTO_IMPORTACAO_ZEUS = 5;
  
      private int visaoAtual;
  
      @EJB
      private ParametrosService parametrosService;
  
      @Inject
      private Conversation conversation;
  
      private ValorHora valorHora;
      private AgendamentoBuscaSistec agendamentoBuscaSistec;
      private AgendamentoExportacaoZeus agendamentoExportacaoZeus;
      private AgendamentoImportacaoZeus agendamentoImportacaoZeus;
  
      private List&lt;ValorHora&gt; listaValorHora;
      private boolean listaValorHoraModificada;
      private List&lt;AgendamentoBuscaSistec&gt; listaAgendamentoBuscaSistec;
      private boolean listaAgendamentoBuscaSistecModificada;
      private List&lt;AgendamentoExportacaoZeus&gt; listaAgendamentoExportacaoZeus;
      private boolean listaAgendamentoExportacaoZeusModificada;
      private List&lt;AgendamentoImportacaoZeus&gt; listaAgendamentoImportacaoZeus;
      private boolean listaAgendamentoImportacaoZeusModificada;
  
      private ParametrosVingentes parametrosVingentes;
  
      public Parametros() {
          this.visaoAtual = VISAO_PARAMETROS_VINGENTES;
      }
  
      @PostConstruct
      public void init(){
          this.conversation.begin();
          this.parametrosVingentes = this.parametrosService.getParametrosVingentes();    
      }
  
      public ParametrosVingentes getParametrosVingentes() {
          return parametrosVingentes;
      }
  
      public List&lt;ValorHora&gt; getListaValorHora(){
          if(this.listaValorHora == null || this.listaValorHoraModificada){
              this.listaValorHoraModificada = false;
              this.listaValorHora = this.parametrosService.listarValorHora();
          }
          return this.listaValorHora;
      }
  
      public List&lt;AgendamentoBuscaSistec&gt; getListaAgendamentoBuscaSistec(){
          if(this.listaAgendamentoBuscaSistec == null || this.listaAgendamentoBuscaSistecModificada){
              this.listaAgendamentoBuscaSistecModificada = false;
              this.listaAgendamentoBuscaSistec = this.parametrosService.listarAgendamentoBuscaSistec();
          }
          return this.listaAgendamentoBuscaSistec;
      }
  
      public List&lt;AgendamentoExportacaoZeus&gt; getListaAgendamentoExportacaoZeus(){
          if(this.listaAgendamentoExportacaoZeus == null || this.listaAgendamentoExportacaoZeusModificada){
              this.listaAgendamentoExportacaoZeusModificada = false;
              this.listaAgendamentoExportacaoZeus = this.parametrosService.listarAgendamentoExportacaoZeus();
          }
          return this.listaAgendamentoExportacaoZeus;
      }
  
      public List&lt;AgendamentoImportacaoZeus&gt; getListaAgendamentoImportacaoZeus(){
          if(listaAgendamentoImportacaoZeus == null || this.listaAgendamentoImportacaoZeusModificada){
              this.listaAgendamentoImportacaoZeusModificada = false;
              this.listaAgendamentoImportacaoZeus = this.parametrosService.listarAgendamentoImportacaoZeus();
          }
          return this.listaAgendamentoImportacaoZeus;
      }
  
      public void atualizarParametrosVingentes(){
          this.parametrosService.atualizarParametrosVingentes(this.parametrosVingentes);
      }
  
      // Other methods
  </code></pre>
  
  <p>And this is the JSF:</p>
  
  <pre><code>&lt;p:fieldset&gt;
      &lt;h:panelGrid columns="2"&gt;
          &lt;h:outputLabel value="Valor da hora:" for="valorHoraVingente" /&gt;
          &lt;p:selectOneMenu id="valorHoraVingente" value="#{parametros.parametrosVingentes.valorHora}"&gt;
              &lt;f:selectItem itemLabel="Selecione" itemValue="#{null}" /&gt;
              &lt;f:selectItems value="#{parametros.listaValorHora}" /&gt;
          &lt;/p:selectOneMenu&gt;
          &lt;h:outputLabel value="Agendamento da Busca do Sistec:" for="agendamentoBuscaSistecVingente" /&gt;
          &lt;p:selectManyCheckbox id="agendamentoBuscaSistecVingente" value="#{parametros.parametrosVingentes.agendamentosBuscaSistec}"&gt;
              &lt;f:selectItem itemLabel="Selecione" itemValue="#{null}" /&gt;
              &lt;f:selectItems value="#{parametros.listaAgendamentoBuscaSistec}" /&gt;
          &lt;/p:selectManyCheckbox&gt;
          &lt;h:outputLabel value="Agendamento da Exportação para o Zeus:" for="agendamentoExportacaoZeusVingente" /&gt;
          &lt;p:selectManyCheckbox id="agendamentoExportacaoZeusVingente" value="#{parametros.parametrosVingentes.agendamentosExportacaoZeus}"&gt;
              &lt;f:selectItem itemLabel="Selecione" itemValue="#{null}" /&gt;
              &lt;f:selectItems value="#{parametros.listaAgendamentoExportacaoZeus}" /&gt;
          &lt;/p:selectManyCheckbox&gt;
          &lt;h:outputLabel value="Agendamento da Importação para o Zeus:" for="agendamentoImportacaoZeusVingente" /&gt;
          &lt;p:selectManyCheckbox id="agendamentoImportacaoZeusVingente" value="#{parametros.parametrosVingentes.agendamentosImportacaoZeus}"&gt;
              &lt;f:selectItem itemLabel="Selecione" itemValue="#{null}" /&gt;
              &lt;f:selectItems value="#{parametros.listaAgendamentoImportacaoZeus}" /&gt;
          &lt;/p:selectManyCheckbox&gt;
      &lt;/h:panelGrid&gt;
      &lt;p:commandButton value="Atualizar" action="#{parametros.atualizarParametrosVingentes}" update="@form" /&gt;
  &lt;/p:fieldset&gt;
  </code></pre>
  
  <p>Like you can see, there's fields bind with the collections that should be fetched with LAZY.</p>
  
  <p>And this is the stack trace:</p>
  
  <pre><code>WARNING: failed to lazily initialize a collection, no session or session was closed
  org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed
      at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
      at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
      at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:122)
      at org.hibernate.collection.PersistentBag.isEmpty(PersistentBag.java:255)
      at javax.faces.component.UIInput.isEmpty(UIInput.java:1257)
      at javax.faces.component.UIInput.validateValue(UIInput.java:1144)
      at javax.faces.component.UISelectMany.validateValue(UISelectMany.java:581)
      at javax.faces.component.UIInput.validate(UIInput.java:967)
      at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
      at javax.faces.component.UIInput.processValidators(UIInput.java:698)
      at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
      at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
      at org.primefaces.component.fieldset.Fieldset.processValidators(Fieldset.java:197)
      at javax.faces.component.UIForm.processValidators(UIForm.java:253)
      at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
      at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
      at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1172)
      at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
      at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
      at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
      at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
      at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
      at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
      at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
      at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
      at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
      at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
      at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
      at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
      at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
      at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
      at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
      at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
      at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
      at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
      at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
      at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
      at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
      at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
      at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
      at java.lang.Thread.run(Thread.java:722)
  </code></pre>
  
  <p>I think that at the end of the method getParametrosVingentes of the service, the EntityManager is clear and all the Entities are detached. Could it be the problem?</p>
  
  <p>I'm running this on Glassfish 3, using Mojarra 2.1.2 and EJB 3.1.
  Thanks for any help.</p>