2 回答

TA貢獻1851條經驗 獲得超5個贊
一對一單向協會
您的代碼設置指向“講師詳細信息”為父級,“教師”為子級關聯。為此,您應該在保留/保存教師實體之前保留/保存 InstructorDetail。OneToOne Unidirectional Association
session.beginTransaction();
session.save(theInstructorDetail);
session.save(ins);
session.getTransaction().commit();
一對一雙向協會
如果您不想在 DB 中關聯 FK,請在 java 休眠中創建雙向關聯:
講師.java
@OneToOne
@JoinColumn(name = "instructor_detail_id")
private InstructorDetail theInstructorDetail;
講師詳情.java
@OneToOne(mappedBy="instructor_detail")
private Instructor theInstructor;
持久邏輯
Instructor ins=new Instructor("elon", "musk", "[email protected]");
InstructorDetail theInstructorDetail=new InstructorDetail("vella Panti Adda", "Acting");
ins.setTheInstructorDetail(theInstructorDetail);
theInstructorDetail.setTheInstructor(ins);
session.beginTransaction();
session.save(theInstructorDetail);
session.getTransaction().commit();
推薦結構
如果您可以對數據庫進行更改,我建議您執行以下操作之一:
備選案文A):更好
作為主表和輔助表,在邏輯上更有意義。也就是說,從表中刪除列并在InsucateDetail表中添加列。然后,只需翻轉java類中的休眠注釋配置(與上述相反)。InstructorInstructorDetailinstructor_detail_idInstructorinstructor_id
選項 B):最佳
由于它是一對一關系,因此若要減少內存上的索引占用空間,請對兩個表使用相同的 PK。然后,您可以使用注釋而不必使用。Instructor_Id@MapsIdBi-directional association
講師詳情.java
@OneToOne
@MapsId
private Instructor theInstructor;

TA貢獻1871條經驗 獲得超13個贊
你已經試過了。
public Instructor(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.theInstructorDetail= new InstructorDetail();
}
我認為你應該開始所有的屬性。
添加回答
舉報