OneToMany Multiple Column Relationship

I have this object Friendship:

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

In friendship, there is only one instance / record of this object (not 2), so there can be no problem when John is a friend of Jane, but not vice versa. Records are also normalized, therefore a friendship member with the lowest identifier user1and another member user2, which means that I can prevent duplicate recording with a simple unique restriction.

To get friendly with a specific user, I execute the request with

WHERE user1 = :me OR user2 = :me.

Can this property be matched with @OneToMany Set<Friendship> User?

( Friendshiphas other properties, so it’s not easy @ManyToMany Set<User> friends)

+3
source share
2

- . , , , - . - :

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

}

, , - - - , ( ) . .

+1

, . @OneToMany? @ManyToMany. . @ManyToMany , user1 - user2. .

0

All Articles