【问题标题】:Spring Data JPA multiple one to many relations from primary key as a foreign keySpring Data JPA从主键作为外键的多个一对多关系
【发布时间】:2021-09-27 23:13:08
【问题描述】:

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

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

  • 身份证号:身份证

  • 决定:是/否

  • swipeFrom:发送赞的个人资料的 ID (profiles.id)

  • swipeTo: 喜欢的个人资料的 id (profiles.id)

  • 时间戳:时间戳

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

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

【问题讨论】:

    标签: java sql hibernate jpa spring-data-jpa


    【解决方案1】:

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

    @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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 2018-04-14
      • 2020-01-08
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 2015-07-16
      相关资源
      最近更新 更多