title: Hibernate Criteria get associated object for collection
body: <p>I have the following Hibernate entities: User, Role and Team. There is also the UserTeamRole entity which is basically a connection between a User, his Role and the Team he is in:</p>
  
  <pre><code>@Entity
  @Table(name = "user_team_role")
  public class UserTeamRole {
  
      private Long id;
      private User user;
      private Role role;
      private Team team;
      [...]  
  }
  </code></pre>
  
  <p>In my JSF managed bean I need to get the User and all the UserTeamRoles for a particular user designated name that I get in a form. I do that in the UserDAO:</p>
  
  <pre><code>public User getUserByDn(String dn) {
          User result = (User) getSessionFactory().getCurrentSession()
                  .createCriteria(User.class)
                  .setFetchMode("userTeamRoles", FetchMode.JOIN)
                  .add(Restrictions.like("dn", dn)).uniqueResult();
          return result;
      }
  </code></pre>
  
  <p>I used the FetchMode because otherwise I would get a LazyInitializationException in the bean because the session was closed at the point that I would need to access the collection.</p>
  
  <p>But, after this I also need to loop through this User.userTeamRoles collection and get the name for each role.</p>
  
  <p>When I do this: </p>
  
  <pre><code>    if (null != u.getUserTeamRoles()) {
          for (UserTeamRole urt : u.getUserTeamRoles()) {
              // here get role for every UserTeamRole
  
              grAuth.add(new SimpleGrantedAuthority(urt.getRole().getName()));
          }
     }
  </code></pre>
  
  <p>I get an exception:</p>
  
  <p><strong>Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session</strong> for the Role entity.</p>
  
  <p>So my question is how can I also get the Role for each UserTeamRole like I did here .setFetchMode("userTeamRoles", FetchMode.JOIN) in <code>getUserByDn</code>.</p>
  
  <p>I tried "chaining" the call to FetchMode but it does not work. I saw you can chain queries on members of associations, but I don't need to query, I just need the Role to be initialized so I can use it further.</p>
  
  <p>I'm using Hibernate 4, Spring 3, JSF 2.</p>
  
  <p>Thanks</p>