title: Hibernate many to many - fetch method eager vs lazy
body: <p>New to Hibernate.</p>
  
  <p>I have User Group many to many relation.
  Three tables : User , Group and UserGroup mapping table.</p>
  
  <p>Entities:</p>
  
  <pre><code>@Entity
  @Table(name = "user")
  public class User {
  
  @Id
  @Column (name = "username")
  private String userName;
  
  @Column (name = "password", nullable = false)
  private String password;
  
  
  @ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
  @JoinTable(name="usergroup", 
              joinColumns={@JoinColumn(name="username")}, 
              inverseJoinColumns={@JoinColumn(name="groupname")})
  private Set&lt;Group&gt; userGroups = new HashSet&lt;Group&gt;();
  
  ... setter and getters
  
  
  
  @Entity
  @Table(name = "group")
  public class Group {
  
  @Id
  @Column(name = "groupname")
  private String groupName;
  
  @Column(name = "admin", nullable = false)
  private String admin;
  
  @ManyToMany(mappedBy = "userGroups", fetch = FetchType.EAGER)
  private Set&lt;User&gt; users = new HashSet&lt;User&gt;();
  
  ... setter and getters
  </code></pre>
  
  <p>Notice that in Group Entity I'm using fetch method EAGER.
  Now, when I'm calling my DAO to retrive all the groups in the system
  using the following criteria:</p>
  
  <pre><code>  Criteria criteria = session.createCriteria(Group.class);
    return criteria.list();
  </code></pre>
  
  <p>I'm getting all the rows from the mappgin table (usergroup) instead of getting the actual number of groups...</p>
  
  <p>for example if i have
  in user table </p>
  
  <pre><code> username password
   -----------------
   user1     user1
   user2     user2
  </code></pre>
  
  <p>in group table</p>
  
  <pre><code> groupname admin
   ---------------
   grp1      user1
   grp2      user2
  </code></pre>
  
  <p>in usergroup table</p>
  
  <pre><code> username groupname
   ------------------
   user1     grp1
   user2     grp2
   user1     grp2
   user2     grp1
  </code></pre>
  
  <p>The result will be the following list - {grp1,grp2,grp2,grp1}</p>
  
  <p>Instead of {grp1,grp2}</p>
  
  <p>If I change in Group Entity the fetch method to LAZY I'm getting the correct results
  but hibernate throws me LazyException in another place...</p>
  
  <p>Please assist what fetch method should I use and why ?</p>
  
  <p>Thanks!</p>