1. 程式人生 > >Hibernate對映多對一關聯關係

Hibernate對映多對一關聯關係

多對一的單向關聯

表於表的關聯可以分為一對一,一對多,多對一和多對多

例如在網路商城中,一個大的商品分類下,有多個小的商品分類,一個小的商品分類下,有多個商品

多對一的單向關聯

例如

tab

<many-to-one name="category" class="com.rbh.examples.Category" outer-join="true">
         	<column name="category_id"></column>
        </many-to-one>

 一對多的關聯

Product與Category是多對一的關係,Product物件維護著對Category物件的參考,如果由Category物件維護多個Product物件的管理,就是一對多單向關聯

        <set name="products">
        	<key column="category_id"></key>
        	<one-to-many class="com.rbh.examples.Product"/>
        </set>

一對多雙向關聯

<many-to-one name="category" class="com.rbh.examples.Category" fetch="select">
            <column name="CATEGORY_ID" precision="8" scale="0" />
        </many-to-one>
 <set name="products">
            <key>
                <column name="CATEGORY_ID" precision="8" scale="0" />
            </key>
            <one-to-many class="com.rbh.examples.Product" />
        </set>

級聯(cascade)

主動方物件執行操作時,被關聯物件(被動方)是否同步執行同一個操作

<set name="products" cascade="save-update">
  <key column="category_id"></key>
  <one-to-many class="com.rbh.examples.Product">
</set>

級聯(cascade)

none  cascade的預設值,表示關聯物件之間沒有任何級聯操作。

save-update 表示主動方物件在呼叫save()、update()和saveorUpdate()方法時對被關聯物件進行級聯操作

delete 表示主動方物件在呼叫save()方法時對被關聯物件進行級聯操作

delete-orphan 只應用於一對多關聯,表面主動物件呼叫delete()方法,此時不被任何一個關聯物件所引用被關聯物件會刪除.

all  關聯物件之間全部操作都順著關聯關係級聯

控制反轉(Inverse)

Hibernate中的一對多的單向或者雙向關聯的情況下,我們可以將"一"方控制權給"多"方,稱為控制反轉(inverse)

<set name="prodects" cascade="save-update" inverse="true">
       <key column="category_id"></key>
       <one-to-many class="com.rbh.examples.Product">
</set>