簡體   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