3

我有这个实体Friendship

@ManyToOne
private User user1;
@ManyToOne
private User user2;
... and other properties of the friendship

每个友谊只有这个实体的一个实例/记录(不是 2 个),所以约翰是简的朋友的情况不会有任何问题,但反之亦然。条目也被规范化,因此 ID 最低的友谊成员是user1,而另一个成员是user2,这意味着我可以通过简单的唯一约束来防止重复条目。

为了获得某个用户的友谊,我执行了一个查询

WHERE user1 = :me OR user2 = :me.

是否可以将其映射到 的@OneToMany Set<Friendship>属性上User

Friendship有其他属性,所以这不简单@ManyToMany Set<User> friends

4

2 回答 2

1

最简洁的答案是不。对于双向提取,我相信完成您所要求的唯一方法是使用命名查询。类似于以下内容:

@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();
}

}

我过去这样做的方法是以某种方式对连接表进行非规范化,无论是通过重复列(在每个方向上映射关联)还是重复行。任何一个都可以让你简化你的获取。

于 2012-05-07T14:33:15.603 回答
0

对的,这是可能的。但是为什么你需要@OneToMany?您可以使用@ManyToMany。它会是一样的。在 @ManyToMany 注释中,您可以指定将存储 id 对 user1 - user2 的表。然后只需对该表进行查询。

于 2012-05-07T14:11:31.293 回答