由於連接表中有其他列,因此無法使用ManyToMany進行映射。它必須被映射爲兩個一對多的關係:
一個用戶(源)有許多友誼
一個朋友是一個源用戶(誰問友誼用戶)
一個朋友是一個目標用戶(誰必須接受友好的用戶)
你應該因此具有以下實體:
@Entity
public class User {
// ...
/**
* the list of friendships asked by this user
*/
@OneToMany(mappedBy = "sourceUser")
private List<Friensdship> frienships = new ArrayList<Friendship>();
}
@Entity
public class Friendship {
// ...
/**
* the user who asked the friendship
*/
@ManyToOne()
@JoinColumn(name = "user_id")
private User sourceUser;
/**
* the user to whom the friendship was asked
*/
@ManyToOne()
@JoinColumn(name = "friend_id")
private User targetUser;
}
如果需要的話,你也可以在用戶中加入反向關係:
/**
* the list of friendships asked to this user
*/
@OneToMany(mappedBy = "targetUser")
private List<Friendship> requestedFriendships = new ArrayList<Friendship>();