There is a way to do this, as I have accomplished nearly the same thing on a self-referential table (joining two instances of the same object type).
IF all of the joined data is in a single table, and you simply need to create a join table, you can do so by using something comparable to this:
private Set<User> users = new HashSet<User>();
..
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name="user_user",
joinColumns = { @JoinColumn( name="user_id") },
inverseJoinColumns = @JoinColumn( name="friend_user_id")
)
public Set<User> getUsers() {
return users;
}
This will create a join column with two separate FK instances, depending on the owning entity (in this case the controlling user user_id). Hibernate will create the join table for you with and control the mapping from the individual "friend" user_id to friend_user_id.
AJ
PenMa wrote:
Hello,
I have a use case where I need to implement something like myspace, and indeed all of the social networking sites, is the ability to connect to friends or colleagues and have them listed on your page.
This is can be done through 2 tables, by self-referential many-to-many relationship,
user Friends
-------- ---------
ID AccountId
ScnName friendId
firstName
LastName
...
Is this is a good design?, If so how to implement this in hibernate,
I am using hibernate 3.2 and annotations and MySQL 5.x, I am trying to something like this
private Set<User> users = new HashSet<User>();
..
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name="user_user",
joinColumns = { @JoinColumn( name="user_id") },
inverseJoinColumns = @JoinColumn( name="user_id")
)
public Set<User> getUsers() {
return users;
}
results in error:
caused by: org.hibernate.MappingException: Repeated column in mapping for collection: com.splashnote.model.User.users column: user_id
And like to implement few queries like
1.Selecting all of your friends
2.Selecting everyone that has you as a friend
3.Query for everyone you are friends with (Mutually Inclusive).
4.Figure out if someone is your Friend.
It would be great if some one has already implemented like this, can share some idea.
Thanks
Pen Ma