(十二)Hibernate中的多表操作(1):單向多對一
阿新 • • 發佈:2017-05-14
art 保存 int gen round t對象 情況 映射文件 拋出異常
- 由“多”方可知“一”方的信息,比如多個員工使用同一棟公寓,員工可以知道公寓的信息,而公寓無法知道員工的信息。
案例一:
- pojo類
public class Department { //公寓類,“一”方 private int id; private String name; //setter和getter方法.... }
public class Employee { //員工類,“多”方 ,既然是多對一,多方知道一放的信息,那麽在多方中必須有一方的對象, private intid; private String name; private Department department; //setter和getter方法 }
- 實體映射文件
Department.hbm.xml如下:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.reiyen.hibernate.domain"> <class name="Department" > <id name="id" > <generator class="native" /> </id> <property name="name" /> </class> </hibernate-mapping>
Employee.hbm.xml如下:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.reiyen.hibernate.domain"> <class name="Employee"> <id name="id"> <generator class="native" /> </id> <property name="name" /> <!-- name="department" name的值必須與Employee中的屬性名一致. --> <many-to-one name="department" column="depart_id" class="Department" /> </class> </hibernate-mapping>
-
<many-to-one >元素建立了department屬性和employee表的外鍵depart_id之間的映射.
- <many-to-one name=”department” column=”depart_id” />這種缺省情況,
- hibernate會默認去department對象中查找主鍵值,因為hibernate默認的是外鍵對應另一個表中的主鍵的,
- 如果想對應department中的其它屬性,如”name”,則可以使用<many-to-one name=”department” column=”depart_id” property-ref=”name”/>也可以使用<many-to-one name=”department” />,這與 <many-to-one name=”depart” column=”depart_id” />的唯一區別就是它的column名也為department了,而不是depart_id.
-
name: 設定待映射的持久化類的屬性名,此外為employee類的department屬性.
column: 設定和持久化類的屬性對應的表的外鍵,此外為employee表的外鍵depart_id.
class(可選):設定持久化類的屬性的類型,此處設定department的類型是Department類.
not-null(可選):如果為true,表示department屬性不能為null,該屬性的默認值為false.當為true時,生成的employee表中depart_id外鍵會設置not-null約束,所以當Hibernate保存Employee對象時,會先檢查它的department屬性是否為null,如果為null,則會拋出異常.
(十二)Hibernate中的多表操作(1):單向多對一