2 Replies Latest reply on Jun 18, 2007 8:35 AM by mazz

    Properly using a OneToMany relationship using EJB 3.0

    Dennis Przybyla Novice

      I am getting the infamous:

      org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed


      I get this when trying to access the one to many relationship.
      I am using JBoss 4.0.5 with ejb3.0.

      I have done an exhaustive search on how to fix this problem and understand that I don't have an ongoing session or something like that. What I can't find is a way to solve the problem. I would like to do this without using hibernate specific annotations or code, but at this point I am open to anything to get my project moving forward. What do I need to do to handle this properly? Is there a tutorial that can show me how to do this (I can't seem to find one).

        • 1. Re: Properly using a OneToMany relationship using EJB 3.0
          Sandor Fiedler Newbie

          Hi,

          you two different options:

          First one is to changed the loading strategy of your relationship by adding the appropriate attributes to the annotation i.e.

          @OneToMany(fetch = FetchType.EAGER)
          .
          This is a standard declaration defined by the spec.

          Second one is a little bit tricky because of the knowledge of cursor going to be closed. A lazy fetched relationship can be fully loaded by iterating over the collection using an iterator of an attached entity. Thus it is enough to call the relationships iterator method and the assoziated entities must be loaded.

          Regards

          • 2. Re: Properly using a OneToMany relationship using EJB 3.0
            mazz Master

            Problem with that second solution is that it leads to the N+1 problem.

            There is a third solution - use LEFT JOIN FETCH.

            If you have a collection that is configure for lazy loading, you can execute a JPQL query that left join fetches the collection you want to eagerly load. There is plenty of info on the net about left join fetches if you want to learn more.

            All of these solutions mentioned in this thread are not hibernate specific.