一、集合映射
1.集合小介
集合映射也是基本的映射,但在開發過程中不會經常用到,所以不需要深刻了解,只需要理解基本的使用方法即可,等在開發過程中遇到了這種問題時能夠查詢到解決方法就可以了。對應集合映射它其實是指將java中的集合映射到對應的表中,是一種集合對象的映射,在java中有四種類型的集合,分別是Set、Map、List還有普通的數組,它們之間有很大的區別:
(1)Set,不可以有重復的對象,對象是無序的;
(2)List,可以與重復的對象,對象之間有順序;
(3)Map,它是鍵值成對出現的;
(4)數組,可以重復,對象之間有順序。
它們之間的區別決定了在開發時使用哪種集合,通常在開發時會使用Set,它內部的對象是無需的,并可以使用迭代器獲取內部對象。這幾種集合想要映射到相應的關系模型的話就必須使用Hibernate提供的映射標簽,<set>、<list>、<map>、<array>。
2.映射小介
繼續討論集合映射的關系模型,集合映射是指一個對象對應著另一個對象集合,在保存時Hibernate會把數據集合保存到相應的表中,并按照自己分配的id把數據保存到數據表中,如果單獨為集合分配了新表,那么會將id分配給集合表的id,那么對應的關系表如下圖:

3.類文件
集合映射是如何通過代碼實現的,接下來具體分析。這里把所有的集合封存到一個類中,這個類我們稱之為CollectionMapping.java,那么它對應的內部代碼如下:
package com.hibernate; import java.util.List; import java.util.Map; import java.util.Set; @SuppressWarnings("rawtypes") public class CollectionMapping { //id private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } //名字 private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } //Set集合 private Set setValues; public Set getSetValues() { return setValues; } public void setSetValues(Set setValues) { this.setValues = setValues; } //List集合 private List listValues; public List getListValues() { return listValues; } public void setListValues(List listValues) { this.listValues = listValues; } //數組集合 private String[] arrayValues; public String[] getArrayValues() { return arrayValues; } public void setArrayValues(String[] arrayValues) { this.arrayValues = arrayValues; } //Map集合 private Map mapValues; public Map getMapValues() { return mapValues; } public void setMapValues(Map mapValues) { this.mapValues = mapValues; } } 該類中封裝了幾種常用的集合,想要轉化為關系模型,就必須來看下文的映射。
4.集合映射
集合的映射其實相當的簡單,只需要添加對應的集合標簽,Hibernate分別提供了集合標簽<set>、<map>、<list>、<array>,通過使用集中標簽來將集合映射為對應的關系表,另外通過添加<key>標簽來實現表外鍵的關聯,其它的屬性通過使用<element>來添加。
CollectionMapping.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> <class name="com.hibernate.CollectionMapping" table="t_collection_mapping"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <set name="setValues" table="t_set_values"> <key column="set_id"></key> <element type="string" column="set_value"></element> </set> <list name="listValues" table="t_list_values"> <key column="list_id"/> <list-index column="list_index"/> <element type="string" column="list_value"/> </list> <map name="mapValues" table="t_map_values"> <key column="map_id"/> <map-key type="string" column="map_key"/> <element type="string" column="map_value"/> </map> <array name="arrayValues" table="t_array_value"> <key column="array_id"/> <index column="array_index" type="integer"></index> <element type="string" column="array_value"/> </array> </class> </hibernate-mapping>
需要注意的是list標簽和array標簽,這兩種集合內的對象是有順序的,所以在添加映射標簽時需要使用list-index或者index標簽來標明對象的順序,而且在添加子標簽時一定要按照順序添加,也就是說先添加<key>標簽,后添加<list-index>標簽,最后添加<element>標簽,否則的話會出現如下錯誤:The content of element type "list" must match "(meta*,subselect?,cache?,synchronize*,comment?,key,(index|list-index),(element|one-to-many|many-to-many|composite-element|many-to-any),loader?,sql-insert?,sql-update?,sql-delete?,sql-delete-all?,filter*)".
5.關系模型
將配置好的對象模型轉化為相應的關系模型,生成的SQL語句如下:
alter table t_array_value drop foreign key FK2E0DD0C067676B68 alter table t_list_values drop foreign key FKE01EC98BF4FCB03 alter table t_map_values drop foreign key FKD169BA107402B585 alter table t_set_values drop foreign key FK7BB8D04A7E79F8BF drop table if exists t_array_value drop table if exists t_collection_mapping drop table if exists t_list_values drop table if exists t_map_values drop table if exists t_set_values create table t_array_value (array_id integer not null, array_value varchar(255), array_index integer not null, primary key (array_id, array_index)) create table t_collection_mapping (id integer not null auto_increment, name varchar(255), primary key (id)) create table t_list_values (list_id integer not null, list_value varchar(255), list_index integer not null, primary key (list_id, list_index)) create table t_map_values (map_id integer not null, map_value varchar(255), map_key varchar(255) not null, primary key (map_id, map_key)) create table t_set_values (set_id integer not null, set_value varchar(255)) alter table t_array_value add index FK2E0DD0C067676B68 (array_id), add constraint FK2E0DD0C067676B68 foreign key (array_id) references t_collection_mapping (id) alter table t_list_values add index FKE01EC98BF4FCB03 (list_id), add constraint FKE01EC98BF4FCB03 foreign key (list_id) references t_collection_mapping (id) alter table t_map_values add index FKD169BA107402B585 (map_id), add constraint FKD169BA107402B585 foreign key (map_id) references t_collection_mapping (id) alter table t_set_values add index FK7BB8D04A7E79F8BF (set_id), add constraint FK7BB8D04A7E79F8BF foreign key (set_id) references t_collection_mapping (id)
生成的對應的數據庫視圖如下:


二、數據操作
1.數據寫入
寫入數據操作,將數據寫入時需要注意創建數據對象,其中的List、Set、Map需要創建數據對象,將數據對象寫入到數據庫中,因為它們三者都是對象接口,所以需要創建一個對象,將對象寫入到數據庫中,具體代碼如下:
@SuppressWarnings({ "unchecked", "rawtypes" }) public void testsave(){ Session session=null; try{ session=HibernateUtils.getSession(); session.beginTransaction(); CollectionMapping cm=new CollectionMapping(); cm.setName("zhangsan"); Set set=new HashSet(); set.add("a"); set.add("b"); cm.setSetValues(set); List list=new ArrayList(); list.add("list1"); list.add("list2"); cm.setListValues(list); String[] str=new String[]{"array1","array2"}; cm.setArrayValues(str); Map map=new HashMap(); map.put("k1","v1"); map.put("k2", "v2"); cm.setMapValues(map); session.save(cm); session.getTransaction().commit(); }catch(Exception e){ e.printStackTrace(); session.getTransaction().rollback(); }finally{ HibernateUtils.closeSession(session); } } 生成的SQL語句如下:
Hibernate: insert into t_collection_mapping (name) values (?) Hibernate: insert into t_set_values (set_id, set_value) values (?, ?) Hibernate: insert into t_set_values (set_id, set_value) values (?, ?) Hibernate: insert into t_list_values (list_id, list_index, list_value) values (?, ?, ?) Hibernate: insert into t_list_values (list_id, list_index, list_value) values (?, ?, ?) Hibernate: insert into t_map_values (map_id, map_key, map_value) values (?, ?, ?) Hibernate: insert into t_map_values (map_id, map_key, map_value) values (?, ?, ?) Hibernate: insert into t_array_value (array_id, array_index, array_value) values (?, ?, ?) Hibernate: insert into t_array_value (array_id, array_index, array_value) values (?, ?, ?)
2.加載數據
加載數據的方法很簡單,它會將表中的數據按照集合加載到對象中,然后只需要獲取相應的對象集合即可。
public void testload(){ Session session=null; try{ session=HibernateUtils.getSession(); session.beginTransaction(); CollectionMapping cm=(CollectionMapping)session.load(CollectionMapping.class, 1); System.out.println("cm.name= "+cm.getName()); System.out.println("cm.list= "+cm.getListValues()); System.out.println("cm.map= "+cm.getMapValues()); System.out.println("cm.array= "+cm.getArrayValues()); System.out.println("cm.set= "+cm.getSetValues()); session.getTransaction().commit(); }catch(Exception e){ e.printStackTrace(); session.getTransaction().rollback(); }finally{ HibernateUtils.closeSession(session); } } 生成的結果:
Hibernate: select collection0_.id as id0_0_, collection0_.name as name0_0_ from t_collection_mapping collection0_ where collection0_.id=? Hibernate: select arrayvalue0_.array_id as array1_0_, arrayvalue0_.array_value as array2_0_, arrayvalue0_.array_index as array3_0_ from t_array_value arrayvalue0_ where arrayvalue0_.array_id=? cm.name= zhangsan Hibernate: select listvalues0_.list_id as list1_0_, listvalues0_.list_value as list2_0_, listvalues0_.list_index as list3_0_ from t_list_values listvalues0_ where listvalues0_.list_id=? cm.list= [list1, list2] Hibernate: select mapvalues0_.map_id as map1_0_, mapvalues0_.map_value as map2_0_, mapvalues0_.map_key as map3_0_ from t_map_values mapvalues0_ where mapvalues0_.map_id=? cm.map= {k1=v1, k2=v2} cm.array= [Ljava.lang.String;@758d8478 Hibernate: select setvalues0_.set_id as set1_0_, setvalues0_.set_value as set2_0_ from t_set_values setvalues0_ where setvalues0_.set_id=? cm.set= [b, a] 三、總結
Hibernate可以持久化以下java集合的實例, 包括java.util.Map, java.util.Set, java.util.SortedMap, java.util.SortedSet, java.util.List, 和任何持久實體或值的數組(使用Set集合類型是最好的選擇)。類型為java.util.Collection或者java.util.List的屬性還可以使用"bag"語義來持久。用于持久化的集合,除了集合接口外,不能保留任何實現這些接口的類所附加的語義(例如:LinkedHashSet帶來的迭代順序)。所有的持久化集合,實際上都各自按照 HashMap, HashSet, TreeMap, TreeSet 和 ArrayList 的語義直接工作。更深入地說,對于一個包含集合的屬性來說,必須把Java類型定義為接口 (也就是Map, Set 或者List等),而絕不能是HashMap, TreeSet 或者 ArrayList。存在這個限制的原因是,在你不知道的時候,Hibernate暗中把你的Map, Set 和 List 的實例替換成了它自己的關于Map, Set 或者 List 的實現。(所以在你的程序中,謹慎使用==操作符。)(說明: 為了提高性能等方面的原因,在Hibernate中實現了幾乎所有的Java集合的接口(為了實現懶加載的一些特性) 。)所有的有序集合類(maps, lists, arrays)都擁有一個由<key> 和 <index> 組成的主鍵。 這種情況下集合類的更新是非常高效的――主鍵已經被有效的索引,因此當Hibernate試圖更新或刪除一行時,可以迅速找到該行數據。集合(sets)的主鍵由<key> 和其他元素字段構成。 對于有些元素類型來說,這很低效,特別是組合元素或者大文本、大二進制字段; 數據庫可能無法有效的對復雜的主鍵進行索引。 另一方面,對于一對多、多對多關聯,特別是合成的標識符來說,集合也可以達到同樣的高效性能。( 附注:如果你希望SchemaExport 為你的<set> 創建主鍵, 你必須把所有的字段都聲明為not-null="true" 。)<idbag> 映射定義了代理鍵,因此它總是可以很高效的被更新。事實上, <idbag> 擁有著最好的性能表現。Bag是最差的。因為bag允許重復的元素值 ,也沒有索引字段,因此不可能定義主鍵。 Hibernate無法判斷出重復的行。當這種集合被更改時,Hibernate將會先完整地移除 (通過一個(in a single DELETE ))整個集合,然后再重新創建整個集合。 因此Bag是非常低效的。
新聞熱點
疑難解答