多對一關聯映射:在多的一端加入一個外鍵指向一的一端,它維護的關系是多指向一
一對多關聯映射:在多的一端加入一個外鍵指向一的一端,它維護的關系是一指向多
也就是說一對多和多對一的映射策略是一樣的,只是站的角度不同
1.多對一(下面示例人員表(Info),民族表(Nation)) 多個人員對應一個民族。要知道,人員表中的外鍵列nation是對應民族表的主鍵列code。所以要在Info.hbm.xml中配置nation外鍵指向民族表。(如下圖所示)
一般需要加上cascade="save-update",加這個配置業屬性目的是,many表和one表一起更新
2.一對多(下面以人員表(Info)和工作簡歷(Work)表為例)每個人員對應個工作簡歷。
首先需要在Info的實體類中加入一個Set<Work> 類型的字段。
然后再Info.hbm.xml中配置一對多。(如下圖所示)
<set name="實體類中集合成員的變量名(works)">
<one-to-many class="Work表">
<key>
<column name="InfoCode" ></colum>
</key>
</set>
3.一對一(人員表與密碼表)每個人對應相應的用戶密碼:(因為外鍵值設置在login表上,所以在login.hbm.xml中配置信息)
4.多對多
數據庫中沒有多對多的關系。只有程序里面有。數據庫中是使用兩個一對多和多對一來實現多對多的。典型的是:中間表
在程序中,如果中間表中沒有其它信息,那就可以不用寫中間表的實體類。
多對多,還可以用在:用戶和角色的關系上。
1.給類加關聯對象(集合對象)
2.給hbm.xml配置
<set name="當前類的集合屬性" table="中間表">
<key column="中間表中與此表對應的外鍵"></key>
<many-to-many class="另外多方對象的類名" column="另外多方對象在中間表中的外鍵"></many-to-many>
</set>
<set name="courses" table="score">
<key column="sno"></key>
<many-to-many class="Course" column="cno"></many-to-many>
</set>
(雙向)
雙向多對一關聯 是最常見的關聯關系。(這也是標准的父/子關聯關系。)
<class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <many-to-one name="address" column="addressId" not-null="true"/> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> <set name="people" inverse="true"> <key column="addressId"/> <one-to-many class="Person"/> </set> </class>
基於外鍵關聯的雙向一對一關聯也很常見。
<class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <many-to-one name="address" column="addressId" unique="true" not-null="true"/> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> <one-to-one name="person" property-ref="address"/> </class>