【问题标题】:Is it possible to use one-to-many and many-to-one in the same entity?是否可以在同一实体中使用一对多和多对一?
【发布时间】:2016-10-24 20:33:26
【问题描述】:

我想修改spring的rest教程。链接here

教程有两个实体:用户和书签(多个书签可以属于一个用户。)

我想稍微修改一下。我想创建一个用户、问题、答案实体 - 一个用户可以有很多问题,一个问题可以有很多答案。

这可能吗? 问题实体的实体定义应该如何?

逻辑是用户可以创建测验。测验可以包含问题,这些问题可能有可能的答案。

你知道实体应该是什么样子吗?

我会感激每一个想法。

【问题讨论】:

  • 测验只能包含一个问题?
  • 一个实体可以参与许多不同的关系——所以是的,这是可能的。
  • @Minjun.Y 感谢您的指出。不,测验可以包含许多问题。 (编辑原帖)

标签: spring hibernate jpa spring-boot spring-data-jpa


【解决方案1】:
Is it possible to use one-to-many and many-to-one in the same entity?

我假设您的问题是,“问题实体”是否可以同时与 Answers 实体具有一对多关系,并与 User 实体具有多对一关系。 对的,这是可能的。只是,在使用注释将实体相互映射时要小心,否则应用程序的性能将严重下降。明智地使用 eager/Lazy fetch。打印出 spring-data-jpa/hibernate 在后台触发的 sql 查询并进行分析。

【讨论】:

    【解决方案2】:

    这绝对是可能的。

    用户

    @Entity
    public class User {
    
    // id and other attributes ommited
    
    // User and Quiz has OneToMany bidirectional relationship. OP hasn't specified that but I think it makes more sense because a quiz most likely will need to know the user who created it.
    @OneToMany (mappedBy="user",  cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
    private List<Quiz> quizes;
    
    // ...
    }
    

    测验

    @Entity
    public class Quiz {
    // id ommitted
    @OneToMany
    private List<Question> questions;
    
    @ManyToOne
    @JoinColumn(name = "user_id") //quiz table will have a column `user_id` foreign key referring to user table's `id` column
    private User user;
    
    // ...
    }
    

    问题

    @Entity
    public class Question {
    // id ommitted
    @OneToMany
    @JoinColumn(name="question_id") // Question and Answer has one-to-many unidirectional relationship. `answer` table has a foreign key `question_id` referring to `question.id` column
    private List<Answer> answers;
    
    // ...
    }
    

    回答

    @Entity
    public class Answer {
    
    // ..more attributes
    }  
    

    注意:

    • 实体关系还取决于您的业务逻辑。
    • 如果双向关系的所有者不同,那么你的客户端代码需要调整。 jpa-joincolumn-vs-mappedby
    • 如果您想将您的表设计为“干净”的,这样一个实体表就没有引用另一个关联实体的外键。您可以创建一个连接表,让 OneToMany 关系“感觉”像 ManyToMany,并使用唯一索引来强制执行 OneToMany。它是由你决定。这个wikibook page解释得很好

    这绝对不是唯一的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2011-05-27
      • 2019-02-26
      • 1970-01-01
      相关资源
      最近更新 更多