title: LazyLoading with spring and hibernate
body: <p>I'm trying to solve my LazyLoading problem, which I worked around by fetchType EAGER in the past. But that cannot be the final solution.</p>
  
  <p>I tried to contruct an example, which does not make much sence the way it is, but demonstrates my problem:
  I have a company, and persons are @ManyToOne by composition.
  Now when I try to access the personList by a calculator, I get this exception:</p>
  
  <pre><code>Schwerwiegend [javax.enterprise.resource.webcontainer.jsf.context] (http--127.0.0.1-8080-4) javax.el.ELException: /tablePersons.xhtml @31,76 value=" #{calculator.getPersonCount(_var)}":
  org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: business.domain.Company.personList, no session or session was closed
  </code></pre>
  
  <p>Maybe someone can help me solving this?</p>
  
  <p>tablePersons.xhtml:</p>
  
  <pre><code>&lt;p:dataTable var="_var" value="#{facade.companies}"&gt;
  &lt;p:column&gt;
  &lt;h:outputText value="#{calculator.getPersonCount(_var)}" /&gt;
  </code></pre>
  
  <p>backing facades:</p>
  
  <pre><code>@Named
  @RequestScoped
  class Facade() {
      @Inject
      Dao dao;
  
      List&lt;Company&gt; companies;
  
      @PostConstruct
      init() {
          companies = Dao.findByNamedQuery("Companies.ALL");
      }
  }
  
  
  @Named
  @RequestScoped
  class Calculator {
      int getPersonCount(Company c) {
          return c.getPersonList().size(); //EX
      }
  }
  </code></pre>
  
  <p>Crud service:</p>
  
  <pre><code>@Stateless
  @Transactional
  class Dao() {
      @PersistenceContext
      private EntityManager em;
  
      //CRUD
  }
  </code></pre>
  
  <p>Entity:</p>
  
  <pre><code>@Entity
  @NamedQueries( {
      @NamedQuery(name = Company.ALL",
                  query = "SELECT c FROM Company c")
  })
  class Company {
      @OneToMany(cascade = CascadeType.ALL)  // fetch=FetchType.EAGER &lt;-ugly, but would work
      List&lt;Person&gt; personList = new LinkedList&lt;Person&gt;();
  }
  </code></pre>
  
  <p>I also already configured the Spring OpenEntityManager in web.xml:</p>
  
  <pre><code>&lt;filter&gt;
      &lt;filter-name&gt;OpenEntityManagerInViewFilter&lt;/filter-name&gt;
      &lt;filter-class&gt;
          org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
      &lt;/filter-class&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;entityManagerFactoryBeanName&lt;/param-name&gt;
          &lt;param-value&gt;entityManagerFactory&lt;/param-value&gt;
      &lt;/init-param&gt;
  &lt;/filter&gt;
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;OpenEntityManagerInViewFilter&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  </code></pre>
  
  <p>Nevertheless it does not work. But I have not more idea why!
  Maybe someone knows more?</p>
  
  <p>tyvm</p>