简体   繁体   English

单个实体的多对多关系-Hibernate

[英]Many-to-many relation of a single entity - Hibernate

I have a simple User entity and would like to implement a ManyToMany relation with another users. 我有一个简单的User实体,并希望与另一个用户实现ManyToMany关系。 The class looks like this: 该类如下所示:

@Entity
public class User {
    @Id
    @GeneratedValue
    private long id;

    private String username;

    @ManyToMany
    private List<User> friends;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public List<User> getFriends() {
        return friends;
    }

    public void setFriends(List<User> friends) {
        this.friends = friends;
    }

    public void addFriend(User user){
        if (friends==null) friends = new ArrayList<User>();
        friends.add(user);
    }
}

This doesn't work how I want however, because I'd like to have only one row in the database for bidirectional relation, in this case it makes two rows, in both directions. 但是,这并不能满足我的要求,因为我只想在数据库中有一行用于双向关系,在这种情况下,它在两个方向上都做成两行。

How can I achieve that? 我该如何实现?

An option is one-to-many with join table . 一个选项与join table一对多

Just make sure to properly update both users participating in the association. 只要确保正确更新参与该关联的两个用户即可。

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

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