简体   繁体   English

与多个连接列的OneToMany关系

[英]OneToMany relation with multiple join columns

I have this entity Friendship : 我有这个实体Friendship

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

Per friendship there is only one instance/record of this entity (not 2), so there can't be any issues where John is a friend of Jane but not the other way around. 根据友谊,这个实体只有一个实例/记录(不是2个),所以John不是Jane的朋友而不是其他方面也不会有任何问题。 The entries are also normalized so the member of the friendship with the lowest ID is user1 , and the other member is user2 , meaning I can prevent duplicatie entries with a simple unique constraint. 条目也被标准化,因此具有最低ID的友谊的成员是user1 ,而另一个成员是user2 ,这意味着我可以使用简单的唯一约束来防止重复条目。

To get the friendships of a certain user I perform a query with 为了获得某个用户的友谊,我执行查询

WHERE user1 = :me OR user2 = :me . WHERE user1 = :me OR user2 = :me

Is it possible to map that onto a @OneToMany Set<Friendship> property of User ? 是否有可能是映射到一个@OneToMany Set<Friendship>的属性User

( Friendship has other properties, so this is not simply @ManyToMany Set<User> friends ) Friendship有其他属性,所以这不仅仅是@ManyToMany Set<User> friends

The short answer is no. 最简洁的答案是不。 For a bi-directional fetch, I believe the only way to do what you're asking is with a named query. 对于双向提取,我相信你所要求的唯一方法是使用命名查询。 Something along the lines of: 有点像:

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

} }

The way I've done this in the past is to de-normalize the join table in some fashion, whether through duplicate columns (mapping an association in each direction), or duplicate rows. 我过去这样做的方式是以某种方式对连接表进行去规范化,无论是通过重复列(在每个方向上映射关联)还是重复行。 Either would allow you to simplify your fetch. 要么允许您简化您的提取。

Yes it is possible. 对的,这是可能的。 But why you need @OneToMany? 但为什么你需要@OneToMany? You can use @ManyToMany. 你可以使用@ManyToMany。 It will be same. 它会是一样的。 In @ManyToMany annotation you can specify table where pairs of ids user1 - user2 will be stored. 在@ManyToMany注释中,您可以指定表,其中将存储id1对user1 - user2。 Then just do query to this table. 然后只需查询此表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM