【Hibernate】Hibernate的集合映射與sort、order-by屬性
常用集合Set、List、Map,相信大家都很熟悉,面試中也會經常問。Set和List都繼承了Collection接口,Set是無序不可重復的,不可以存儲相同的元素;而Lsit是順序存儲的,可存儲重復元素。Map不是繼承Collection的,Map提供key到value的映射,Map也是不可重復的(key不可重復),一個Map中不能包含相同的key,每個key只能映射一個value。
持久化類的屬性是集合時,要把它們存到數據庫中,需要增設數據庫表來完成映射工作。例如一個學生的教育背景可能不止一個,這個時候持久化類的屬性是集合,這個時候數據庫就需要再提供一張數據庫表來存儲。
由上圖可以看出,集合的映射應該怎么寫了。集合的映射大致一樣,我們用Set的映射來詳細說明。
<set name="education" table="student_education" order-by=" education DESC"> <key column="student_id"></key> <element type="string" column="education"></element> </set>
name屬性是指對象的集合屬性名,table屬性是指集合表(數據庫表)的名稱,key子元素是指集合外鍵的列名,element子元素用來存放集合元素的列的信息,order-by屬性是指查詢數據庫時指定order by 子句,這是在數據庫中的排序。對於Set的排序,還有另外一個屬性sort,它是在內存中排序的,默認是unsorted,sort還有其它兩個值:natural和comparatorClass,當使用sort屬性時,要求使用的是可以排序的Set,例如TreeSet等。
List的映射:
<list name="education" table="student_education"> <key column="student_id"></key> <list-index column="list_id"></list-index> <element type="string" column="education"></element> </list>
List的映射與Set很相似,多了一個list-index子元素,是指定List的索引對應於集合表中的哪個字段。因為List是有序的,可以通過索引來取值。也正因為有序,所以不可以使用sort屬性進行排序。
Map的映射:
<p><map name="education" table="student_education"></p><p> <keycolumn="student_id"></key></p><p> <map-keytype="string" column="map_key"></map-key></p><p> <element type="string"column="education"></element></p><p></map></p>
map-key子元素是指定Map的key值對應集合表中的哪個字段。
除了這3個常用的集合的映射,hibernate還提供了另外兩種集合的映射:數組和Bag。數組性質跟List相似,但是數組的長度不可變;Bag也與List相似,但是它是無序可重復的。因此數組的映射與List基本一樣:
<array name="education" table="student_education"> <key column="student_id"></key> <list-index column="list_id"></list-index> <element type="string" column="education"></element> </array>
而Bag的映射就比List少一個list-index子元素:
<bag name="education" table="student_education"> <keycolumn="student_id"></key> <elementtype="string" column="education"></element> </bag>
注意:
使用集合屬性時,一定要使用接口,而不能聲明為具體實現類。因為經過session操作后,集合就變成hibernate自己的集合實現類。
最好再整理一次關於sort也order-by屬性的使用:
由於Set與Map都是無序的,所以我們可以使用sort或者order-by屬性對它們進行排序。sort是在內存中排序的,要求使用的Set與Map也是可排序的。這種排序方法不建議使用,使用較多的,排序也比較快的是使用order-by屬性,直接在數據庫中排序。