6 Replies Latest reply on Oct 9, 2008 9:40 AM by Bram Biesbrouck

    Please help me understand lazy fetching of a ManyToMany collection.

    Bram Biesbrouck Newbie

      Hi everybody,


      I'm having some problems using a session-scoped entity bean that contains a ManyToMany member that's loaded lazily.


      @Entity
      @Name("member")
      @Table(name="person")
      public class Member implements Serializable
      {
         private static final long serialVersionUID = 5179242727836683375L;
         
         private Integer id;
         private Set<MemberRole> roles;
      
         @Id @GeneratedValue
         public Integer getId()
         {
            return id;
         }
         public void setId(Integer id)
         {
            this.id = id;
         }
         @ManyToMany
         @JoinTable(
                    name="person_company_membership",
                    joinColumns = { @JoinColumn( name="person") },
                    inverseJoinColumns = @JoinColumn( name="company")
            )
         //@JoinTable(name = "MemberRoles", joinColumns = @JoinColumn(name = "MEMBER_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
         public Set<MemberRole> getRoles()
         {
            return roles;
         }
         public void setRoles(Set<MemberRole> roles)
         {
            this.roles = roles;
         }
      }



      When I log in, the entity bean is loaded from the DB and outjected as an entity bean.



      @Name("testAuthenticator")
      public class Authenticator
      {
         @In
         private EntityManager entityManager;
         
         @In
         private Identity identity;
      
         public boolean authenticate() 
         {
            try
            {            
               Member member = (Member) entityManager.createQuery(
                  "from Member where id=1").getSingleResult();
               
               Contexts.getSessionContext().set("authenticatedMember", member);
               
               for ( MemberRole mr : member.getRoles() )
               {
                  identity.addRole(mr.getName());
               }
               
               return true;
            }
            catch (NoResultException ex)
            {
               return false;
            }      
         }
      
      }



      Now the problem: when getRoles() is subsequently called on the bean, a LazyInitializationException is thrown. I know I could let the collection be eagerly fetched, but I would like to understand why the session doesn't manage to load it lazily?


      anyone?


      b.