java - Spring Data JPA从主键作为外键的多个一对多关系
问题描述
我正在开发类似 tinder 的 Spring Boot 和 Angular Web 应用程序,但坚持在 JPA 中建立关系(我已经在 pgAdmin 中的 postgreSQL 数据库中完成了关系)我尝试了@OneToMany、@JoinColumns 和其他方法,但不知道了解如何制作它以及是否可以建立这样的关系,因为我没有在任何网站上找到这样的例子(当然包括 Stackoverflow)
当一个人向右滑动时,另一个人的应用程序将插入到 Swipes
身份证:身份证
决定:是/否
swipeFrom:发送喜欢的个人资料的ID(profiles.id)
swipeTo: 喜欢的个人资料的 id (profiles.id)
时间戳:时间戳
在所有其他表格中,它都会像上面一样工作
这样的关系可能吗? 如果没有,我该怎么办?也许只是保持原样,然后在删除父级时在方法中手动删除 Matches、Swipes 等?
解决方案
虽然我不知道你尝试了什么,但这是可能的。如果您想要双向映射,您将拥有:
@Entity
@Table(name = "profiles")
public class Profile {
// other fields
@OneToMany(mappedBy = "sender", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Message> sentMessages = new ArrayList<>();
@OneToMany(mappedBy = "receiver", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Message> receivedMessages = new ArrayList<>();
// other collections for swipes, matches and timers
}
@Entity
@Table(name = "messages")
public class Message {
// other fields
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "message_from")
private Profile sender;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "message_to")
private Profile receiver;
}
这同样适用于其他表格(滑动、匹配、计时器)。您用于@JoinColumn
指定要将哪个外键映射到哪个字段。
如果您想要单向映射或其他东西,我鼓励您查看Vlad Mihalcea的文章The best way to map a @OneToMany relationship with JPA and Hibernate。
注意:如果您想获取带有已发送和已接收消息的配置文件,则需要使用 Criteria API(或其他方法)。如果你想尝试类似的东西:
@Query("from Profile p join fetch p.sentMessages join fetch p.receivedMessages where p.id = :id")
Optional<Profile> findProfileByIdFetchSendAndReceivedMessages(int id);
或者
@Override
@EntityGraph(attributePaths = { "sentMessages", "receivedMessages" })
Optional<Profile> findById(int id);
你会得到MultipleBagFetchException
.
由于有很多关于这个主题的精彩文章,我现在不再赘述。例如,如果遇到此问题,您可以查看另一个Vlad Mihalcea的文章The best way to fix the Hibernate MultipleBagFetchException 。
推荐阅读
- json - jq - 将复杂的 JSON 解析为字符串
- google-kubernetes-engine - 使用 nginx 在 GKE 中使用静态 IP 和金丝雀部署
- .net - 使用 Confluent 的 .NET Client for Apache Kafka 清除 Kafka 主题
- c# - 从复制过程中被覆盖的数组中的类中指向数组的最佳方法是什么?
- scala - 从列表中的元素构建类实例
- sql - 安全地编写动态 SQL,使用一个示例函数来估计任何视图中的行
- java - 如何在Java中将多对多关系建模为类?
- c++ - 如果必须包含西里尔字符,如何将 char* 转换为 std::string?
- javascript - 输入字段为空时如何清除div输出?
- java - Android Studio:从 Run 'app' 安装的应用程序和从 build/outputs/apk/debug/app-debug.apk 安装的应用程序是不同的