繁体   English   中英

是否可以在同一实体中使用一对多和多对一?

[英]Is it possible to use one-to-many and many-to-one in the same entity?

我想修改Spring的其余教程。 连结这里

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

我想对其进行一些修改。 我想创建一个用户,问题,答案实体-一个用户可以有很多问题,而一个问题可以有很多答案。

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

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

在此处输入图片说明

任何想法,实体应该是什么样子?

我将不胜感激。

绝对有可能。

用户

@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页面解释得很好

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

Is it possible to use one-to-many and many-to-one in the same entity?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM