![](/img/trans.png)
[英]Why Spring JPA Bidirectional OneToMany and ManyToOne is not updating the foreign key column?
[英]JPA Entity best way for ManyToOne Bidirectional Relationship with Foreign Key
考慮下表結構和關系。
Teacher
id(pk),
tname,
subject_id(fk),
subject_name
Subject
sid(pk),
sname,
subject_learning_curve
TEACHER(關系所有者)到 SUBJECT 多對一,雙向關系
我在 intellij 中使用了持久性工具window 。 它基於數據源自動為數據庫中的所有關系生成實體。
在實體中它是這樣生成的
@Entity
//using lombok for getters and setters
public class TEACHER{
@Id
@GeneratedValue
private Long id;
private String tname;
private long subject_id;
private String subject_name;
@ManyToOne
@JoinColumn(name = "subject_id",referencedColumnName="sid")
private Subject subjectBySid; //is this fine to have a reference like this
}
或下面的第二種方法
@Entity
//using lombok for getters and setters
public class Teacher{
@Id
@GeneratedValue
private Long id;
private String tname;
@ManyToOne
@JoinColumn(name = "subject_id",referencedColumnName="sid")
private Subject subject; //or just this it will suffice all use case,like if i just want to read Teacher data and just the sid not the whole subject row
}
同樣,主題也將具有指向教師表的參考。
基於以下幾點,有人可以提供見解。
@JoinColumn(name = "subject_id",referencedColumnName="sid")
中獲取該特定字段@JoinColumn(name = "subject_id",referencedColumnName="sid")
注釋會解決這個問題,它應該在 TEACHER.subject_id 中具有價值以下是我對您的問題的回答和建議:
1.以上兩種寫實體的方式,哪一種是最理想和正確的。
方法 2 是編寫實體的正確方法。 一旦您定義了與另一個實體的
@ManyToOne
關系,就無需定義特定於該實體的列。
2. 從 Hibernate 和 JPA 的角度來看哪個更高效。
JPA is the specification for management of relational data in Java and Hibernate is the Object-Relational Mapping(ORM) tool that saves the state of objects into DB. 簡單來說,Hibernate就是JPA的實現。 因此,比較它們不應該是一個問題。 您可以將 Hibernate 與其他可與 Spring 框架(如 iBatis、EclipseLink 等)一起使用的 ORM 工具進行比較。
3. 根據我選擇編寫實體的方法生成的 sql 會有什么不同嗎?
不,生成的 SQL 將是相同的。 但是,要生成 SQL,您可以使用不同的方法,例如
@NativeSqlQuery
、Hibernate Query Language(HQL)
等。
4.如果我采用第二種方法,查詢記錄並將其保存到數據庫或檢索會更容易。
您絕對應該使用第二種方法來實現清晰、直接和相關的方法。 如果您考慮面向對象語言和關系數據庫管理的原則,則第一種方法的核心是錯誤的。 當您可以通過映射輕松鏈接它們時,無需創建額外的列、代碼、實體屬性和其他錯誤。
5.當我在實體中獲取數據時,TEACHER 中的 subject_id 是否有價值,或者它只是一個名為 subject 的引用,我不會在 TEACHER.subject_id 或 @JoinColumn(name = "subject_id",referencedColumnName= 中獲取該特定字段"sid") 注釋會解決這個問題,它應該在 TEACHER.subject_id 中具有價值
在您的數據庫中,您的
Teacher
表中應該有一個subject_id
列,該列將作為外鍵並引用Subject
表的sid
列。 這發生在數據庫端。
在您的面向對象端(Spring),您可以使用創建 object 參考為Subject
to map withStudent
,或者您可以直接使用HQL 或 NativeQuery中的字段subject_id
來執行數據庫操作並保存數據。 因此,您將在Teacher
實體中獲得subject_id
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.