[英]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
}
注意:
這絕對不是唯一的解決方案。
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.