我想修改一下spring的休息教程。链接here
本教程有两个实体:用户和书签(许多书签可以属于一个用户。)
我想稍微修改一下。我想创建一个用户,问题,答案实体 - 用户可以有很多问题,一个问题可以有很多答案。
这可能吗? 问题实体的实体定义应该如何?
逻辑是用户可以创建测验。测验可以包含问题,这些问题可能有答案。
任何想法实体应该如何?
我很感激每一个想法。
答案 0 :(得分: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
}
请注意:
这绝对不是唯一的解决方案。
答案 1 :(得分: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查询并进行分析。