Hi,
I'm trying to implement a friendship relation using a join table. However, this is slightly different from other cases in examples on two perspectives:
1) Friendship is in his nature a bidirectional relationship.
Code:
A friend of B => B friend of A
2) No another table to join, it joins on itself
Without forgetting to mention that I'm a newbie, I've tried to implement like this:
Code:
@Entity
public class User {
private long id;
private List<User> friends;
@Id @GeneratedValue
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@ManyToMany
@JoinTable(name="UserFriend",
joinColumns=
@JoinColumn(name="userId", referencedColumnName="id"),
inverseJoinColumns=
@JoinColumn(name="friendId", referencedColumnName="id"))
public List<User> getFriends() {
return friends;
}
public void setFriends(List<User> friends) {
this.friends = friends;
}
}
My first question is:
I didn't experiment on it enough to see if this is really working, or error prone? So is it?
Secondly, this design implicate redundant information to be stored in the db. Suppose User1 and User2 are friends, then this relation is in two rows like (User1, User2) and (User2, User1). Is there a more elegant way to accomplish this relation?
And last, but not least, since I'm in a development environment, I rely on automatic schema generation. Upon examination of the UserFriend join table created by hibernate, I've noticed that there is no primary key, or a unique index on the table, although the foreign keys are present. Could this result a performance loss, and do I break anything if I add a primary key?
Thanks
(Jboss 4.2, mysql 5.0.45, seam 2.0.2 on ubuntu)