Hibernate之關係映射

Hibernate封裝了JDBC大部分的API,使我們對關係型數據庫的訪問轉向面積對象的編程實現,使數據訪問層的代碼得到簡化,而對於Hibernate中實體與表的映射是學習Hibernate的重點,也是難點。這裏簡單總結一下我在學習Hibernate過程中,關於映射的部分總結,其中多對多和一對一的映射在理解上基本無難度,而一對多相對來說比較容易出錯。

一對多和多對一
這裏寫圖片描述

<class name="Employee" table="employee">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name" type="string"/>
        <many-to-one name="department" class="Department"/>
  </class>

<class name="Department" table="department">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name" />
        <set name="employees">
            <key column="departmentId"></key>
            <one-to-many class="Employee"/>
        </set>
  </class>

由以上的Employee和Dempartment的映射文件可以得到它們的表。
Table Dempartment

Column Type
id int(11)
name varchar(255)

Table Employee

Column Type
id int(11)
name varchar(255)
departmentId int(11)

分析:Employee和Department的關聯關係爲多對一,由映射文件可知,Department沒有外鍵,而Employee有外鍵。這裏可以這樣理解,我們一般在多的一方設置外鍵,這樣外鍵的取值就會相對集中,兩個類的屬性分別對應映射文件的class標籤下的屬性標籤,我們主要看相關聯的屬性。根據表格可以看出,外鍵的列名稱是由對方的映射文件來設置的,就像Employee的外鍵departmentId是由Department的來設置的。所以Employee映射文件中many-to-one標籤只需要配上對應的Employee類上的department屬性名,以及其關聯的對方類名就可以了。至於Department的映射文件中就需要說明其employees屬性的類型和關聯對方外鍵的名稱,並說明one-to-many的關聯關係,也就是set標籤。

一對一
基於外鍵的一對一關聯。

<class name="IdCard" table="idcard" lazy="true">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="number" type="string" column="number" not-null="true"/>
        <many-to-one name="person" class="Person" column="personId" unique="true"></many-to-one>
</class>

<class name="Person" table="person" lazy="true">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name" type="string" column="name" not-null="true"/>
        <one-to-one name="idCard" class="IdCard" property-ref="person"/>
 </class>

由以上的IdCard和Person的映射文件可以得到它們的表。
Table IdCard

Column Type
id int(11)
number varchar(255)
personId int(11)

Table Person

Column Type
id int(11)
name varchar(255)

分析:一對一的關聯關係與一對多的外鍵設置相反,是由有外鍵方設置的。有外鍵方(many-to-one)需要設置column(外鍵名)和unique(限制唯一的外鍵關係)。無外鍵方(one-to-one)需要設置property-ref(即對方外鍵中對應屬性的名字)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章