[英]how to implement one-to-one foreign key relation mapping in hibernate
我正在嘗試實現one to one
hibernate
關系mapping
而我是休眠技術的新手。 我的兩個實體類是Employee
和Client
。 客戶應該在數據庫表中有一個employee ID
列作為外鍵; 即this
客戶由this
員工處理。 現在有兩個jsp頁面,通過這些頁面我將提交員工和客戶的詳細信息。 首先,我將添加/提交員工jsp。 然后在客戶端jsp頁面上,將有一個包含employeeID作為其值的選擇框。 我已經完成了我的jsp部分。 但是我懷疑客戶與員工之間的一對一關系。 所以我提供了我的代碼文件。 下面是我的代碼:
員工類別:
public class RWEmp {
private int id;
private String strName;
private String strContactNum;
private String strDateOfJoining;
private String strDesignation;
public RWEmp(){
}
// getter/setters
}
客戶類別:
public class RWClient {
private int id;
private String strName;
private RWEmp poc_emp; // point of contact employee as employee object
public RWClient(){
}
// getter/setters
}
employee.hbm.xml很簡單。 即沒有關系。 但是客戶與雇員對象has a
關系。
client.hbm.xml:
<hibernate-mapping>
<class name="com.rightwave.entities.RWClient" table="client_master">
<id name="id" type="int">
<generator class="increment" />
</id>
<property name="strName" type="string" column="cl_name" />
<many-to-one name="poc_emp" class="com.rightwave.entities.RWEmp" column="poc_emp" unique="true"></many-to-one>
</class>
</hibernate-mapping>
堅持班:
public class PersistEntities {
public void clientPersist() {
Session session=Factory.getSession();
Transaction tr=session.beginTransaction();
RWEmp rwEmp =new RWEmp();
rwEmp.setId(2); // this will come from jsp page <select> value. I am doubtful of this, explained below in question.
RWClient rwClient1=new RWClient("wso2",rwEmp);
session.save(rwClient1);
session.flush();
tr.commit();
session.close();
}
}
在這里,我不確定這個藍圖是對還是錯。 我可以設置員工ID,該ID將來自我的客戶端jsp頁面(來自<select>
框中)。 我很困惑,因為在這里我僅設置員工ID,該ID必須已經存在才能成為客戶的有效外鍵。 但是,沒有檢查來驗證此雇員ID是否已經存在。 Employee對象肯定會(從employee.jsp
保存)在客戶端對象之前。 我做對了嗎?
與兩個實體建立一對一關系時,兩個實體都被分配了相同的主鍵。 應該在Client
表上聲明一個特殊的外部標識符生成器,以從Employee
表中獲取主鍵值。 添加constrained="true"
以確保Employee
存在。
<hibernate-mapping>
<class name="com.rightwave.entities.RWClient" table="client_master">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="foreign">
<param name="property">poc_emp</param>
</generator>
</id>
<one-to-one name="poc_emp" class="com.rightwave.entities.RWEmp"
constrained="true"></one-to-one>
<property name="strName" type="string" column="cl_name" />
</class>
</hibernate-mapping>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.