java - 相同实体关系的休眠辅助表
问题描述
我有一个保存用户信息的 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(被关注的人)。
提前致谢!
解决方案
您需要的是一个单独的表来存储此以下关系(多对多)。最简单的方法是使用@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
,这基本上意味着您必须向followers
Set 插入/删除实例以更改给定配置文件的跟随关系。
如果您想向关系表(即表)添加其他列,也请参阅此内容following
推荐阅读
- kotlin - 无法解析 org.jetbrains:kotlin-css-jvm:1.0.0-pre.31-kotlin-1.2.41
- haskell - 使用折叠将字符串拆分为给定长度的字符串列表
- python - 使用自定义类别从 Pandas 制作饼图
- c++ - 指针未分配/释放时的 C++ 触发函数
- ios - 在 iOS 上添加 firebase_core 后 Flutter 返回错误
- java - 如何使用谷歌视觉 API 进行直接网络远程处理
- sql - 使用 TypeORM 和 NestJS 原始查询返回插入的 id:await connection.manager.query(`INSERT INTO
- linux - 从 Windows 引用文件(正斜杠路径)会出错,而 Linux 也一样
- import - Amcharts - 导入 am4core 失败 - 无法在模块外使用导入语句
- matplotlib - 如何在 matplotlib 中绘制多个图?