由于连接表中有其他列,因此无法使用多对多进行映射。它必须映射为两个 OneToMany 关系:
一位用户(来源)有许多友谊
One Friendship is for one source User(请求友谊的用户)
一个好友是一个目标用户(必须接受好友的用户)
因此,您应该拥有以下实体:
@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;
}
如果需要,您还可以在 user 中添加反向关系:
/**
* the list of friendships asked to this user
*/
@OneToMany(mappedBy = "targetUser")
private List<Friendship> requestedFriendships = new ArrayList<Friendship>();