title: Hibernate recursive many-to-many association with the same entity
body: <p>Another Hibernate question... :P</p>
  
  <p>Using Hibernate's Annotations framework, I have a <code>User</code> entity. Each <code>User</code> can have a collection of friends: a Collection of other <code>User</code>s. However, I have not been able to figure out how to create a Many-to-Many association within the <code>User</code> class consisting of a list of <code>User</code>s (using a user-friends intermediate table).</p>
  
  <p>Here's the User class and its annotations:</p>
  
  <pre><code>@Entity
  @Table(name="tbl_users")
  public class User {
  
      @Id
      @GeneratedValue
      @Column(name="uid")
      private Integer uid;
  
      ...
  
      @ManyToMany(
              cascade={CascadeType.PERSIST, CascadeType.MERGE},
              targetEntity=org.beans.User.class
      )
      @JoinTable(
              name="tbl_friends",
              joinColumns=@JoinColumn(name="personId"),
              inverseJoinColumns=@JoinColumn(name="friendId")
      )
      private List&lt;User&gt; friends;
  }
  </code></pre>
  
  <p>The user-friend mapping table has only two columns, both of which are foreign keys to the <code>uid</code> column of the <code>tbl_users</code> table. The two columns are <code>personId</code> (which should map to the current user), and <code>friendId</code> (which specifies the id of the current user's friend).</p>
  
  <p>The problem is, the "friends" field keeps coming out null, even though I've pre-populated the friends table such that all the users in the system are friends with all the other users. I've even tried switching the relationship to <code>@OneToMany</code>, and it still comes out null (though the Hibernate debug output shows a <code>SELECT * FROM tbl_friends WHERE personId = ? AND friendId = ?</code> query, but nothing else).</p>
  
  <p>Any ideas as to how to populate this list? Thank you!</p>