我有这个实体 Friendship
:
@ManyToOne
private User user1;
@ManyToOne
private User user2;
... and other properties of the friendship
对于每个友谊,此实体只有一个实例/记录(不是 2 个),因此 John 是 Jane 的 friend 而不是其他方式不会有任何问题。条目也被规范化,因此 ID 最低的友谊成员是 user1
, 另一个成员是 user2
,这意味着我可以使用简单的唯一约束来防止重复条目。
为了获得某个用户的友谊,我执行了一个查询
WHERE user1 = :me OR user2 = :me
.
是否可以将其映射到 @OneToMany Set<Friendship>
User
的属性(property)?
( Friendship
有其他属性,所以这不是简单的 @ManyToMany Set<User> friends
)
最佳答案
简短的回答是否定的。对于双向获取,我相信唯一的方法就是使用命名查询。类似的东西:
@Entity
@NamedQuery(name="User.friendships", query="
select u
from User u
where u in (
select f.User1
from Friendship f
where f.User2.id = :userId
) or u in (
select f.User2
from Friendship f
where f.user1.id = :userId
)")
public class User {
private Set<User> friends = new HashSet<User>()
public Collection<User> getFriendships(Session s) {
return s.getNamedQuery("User.friendships")
.setParameter("userId", this.id)
.list();
}
我过去这样做的方法是以某种方式对连接表进行非规范化,无论是通过重复列(在每个方向映射关联)还是重复行。两者都可以让您简化抓取。
关于java - 具有多个连接列的 OneToMany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10483346/