首页 > 解决方案 > 相同实体关系的休眠辅助表

问题描述

我有一个保存用户信息的 Profile 类。此应用程序的功能之一是“关注”您选择的另一个配置文件。我在设计数据库和建立链接时遇到了麻烦,既要编写模型代码又要编写存储库(这只是保存的问题吗?)。

我的 Profile 类如下所示:(为简单起见,省略了与问题和 getter/setter 无关的字段)

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.*;

@Entity
@Table(name = "USERS")
public class Profile implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Size(max = 32)
    @Column(nullable = false)
    private String name;

    @Size(max = 16)
    @Column(unique=true, nullable = false)
    private String username;

    @Email
    @Column(unique=true)
    private String email;

    @ManyToOne
    @JoinColumn(name="profile_id")
    private Profile profile;

    @OneToMany(mappedBy = "profile")
    private List<Profile> friends = new ArrayList<>();


    public Profile() {
    }

    // other getters/setters

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

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

    public void addFriend(Profile friend) {
        this.friends.add(friend);
    }
}


这将创建一个在用户表中null调用的字段。profile_id我做了一些研究,似乎使用@SecondaryTable注释创建另一个表可能会奏效。我研究过的教程并没有解决我的疑问。我想对此事有所了解,并尽可能避免创建不同的实体。

理想情况下,我会有一张带有自己 id 的表,所有者的 id(被关注的人)和目标的 id(被关注的人)。

提前致谢!

标签: javaspringhibernate

解决方案


您需要的是一个单独的表来存储此以下关系(多对多)。最简单的方法是使用@ManyToMany

@Entity
@Table(name = "USERS")
public class Profile implements Serializable {


        @ManyToMany(cascade = CascadeType.ALL)
        @JoinTable(name="following", 
                joinColumns={@JoinColumn(name="user_id")}, 
                inverseJoinColumns={@JoinColumn(name="follower_id")})
        private Set<Profile> followers = new HashSet<Profile>();

        @ManyToMany(mappedBy = "followers", cascade = CascadeType.ALL)
        private Set<Profile> followBy = new HashSet<Profile>();
}

它将被映射到一个名为的关系表following,该表具有以下架构:

---------------------------------
| column      | FK              |
=================================
| user_id     | FK to users.id  |
---------------------------------
| follower_id | FK to users.id  |
---------------------------------

因此,给定用户 A ,该字段followers是 A 关注的所有用户。该字段followBy是所有关注A的用户。

另外,请注意mappedBy设置。这意味着您必须使用该字段followers来维护此跟随关系而不是该字段followBy,这基本上意味着您必须向followersSet 插入/删除实例以更改给定配置文件的跟随关系。

如果您想向关系表(即表)添加其他列,也请参阅此内容following


推荐阅读