首页 > 解决方案 > Spring Data JPA从主键作为外键的多个一对多关系

问题描述

我正在开发类似 tinder 的 Spring Boot 和 Angular Web 应用程序,但坚持在 JPA 中建立关系(我已经在 pgAdmin 中的 postgreSQL 数据库中完成了关系)我尝试了@OneToMany、@JoinColumns 和其他方法,但不知道了解如何制作它以及是否可以建立这样的关系,因为我没有在任何网站上找到这样的例子(当然包括 Stackoverflow)

当一个人向右滑动时,另一个人的应用程序将插入到 Swipes

在所有其他表格中,它都会像上面一样工作

这样的关系可能吗? 如果没有,我该怎么办?也许只是保持原样,然后在删除父级时在方法中手动删除 Matches、Swipes 等?在此处输入图像描述

标签: javasqlhibernatejpaspring-data-jpa

解决方案


虽然我不知道你尝试了什么,但这是可能的。如果您想要双向映射,您将拥有:

@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 。


推荐阅读