Java的Hibernate框架中集合類數(shù)據(jù)結(jié)構(gòu)的映射編寫教程
一、集合映射
1.集合小介
集合映射也是基本的映射,但在開發(fā)過程中不會經(jīng)常用到,所以不需要深刻了解,只需要理解基本的使用方法即可,等在開發(fā)過程中遇到了這種問題時能夠查詢到解決方法就可以了。對應(yīng)集合映射它其實是指將java中的集合映射到對應(yīng)的表中,是一種集合對象的映射,在java中有四種類型的集合,分別是Set、Map、List還有普通的數(shù)組,它們之間有很大的區(qū)別:
(1)Set,不可以有重復(fù)的對象,對象是無序的;
(2)List,可以與重復(fù)的對象,對象之間有順序;
(3)Map,它是鍵值成對出現(xiàn)的;
(4)數(shù)組,可以重復(fù),對象之間有順序。
它們之間的區(qū)別決定了在開發(fā)時使用哪種集合,通常在開發(fā)時會使用Set,它內(nèi)部的對象是無需的,并可以使用迭代器獲取內(nèi)部對象。這幾種集合想要映射到相應(yīng)的關(guān)系模型的話就必須使用Hibernate提供的映射標(biāo)簽,<set>、<list>、<map>、<array>。
2.映射小介
繼續(xù)討論集合映射的關(guān)系模型,集合映射是指一個對象對應(yīng)著另一個對象集合,在保存時Hibernate會把數(shù)據(jù)集合保存到相應(yīng)的表中,并按照自己分配的id把數(shù)據(jù)保存到數(shù)據(jù)表中,如果單獨為集合分配了新表,那么會將id分配給集合表的id,那么對應(yīng)的關(guān)系表如下圖:
3.類文件
集合映射是如何通過代碼實現(xiàn)的,接下來具體分析。這里把所有的集合封存到一個類中,這個類我們稱之為CollectionMapping.java,那么它對應(yīng)的內(nèi)部代碼如下:
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; } //數(shù)組集合 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; } }
該類中封裝了幾種常用的集合,想要轉(zhuǎn)化為關(guān)系模型,就必須來看下文的映射。
4.集合映射
集合的映射其實相當(dāng)?shù)暮唵?,只需要添加對?yīng)的集合標(biāo)簽,Hibernate分別提供了集合標(biāo)簽<set>、<map>、<list>、<array>,通過使用集中標(biāo)簽來將集合映射為對應(yīng)的關(guān)系表,另外通過添加<key>標(biāo)簽來實現(xiàn)表外鍵的關(guān)聯(lián),其它的屬性通過使用<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標(biāo)簽和array標(biāo)簽,這兩種集合內(nèi)的對象是有順序的,所以在添加映射標(biāo)簽時需要使用list-index或者index標(biāo)簽來標(biāo)明對象的順序,而且在添加子標(biāo)簽時一定要按照順序添加,也就是說先添加<key>標(biāo)簽,后添加<list-index>標(biāo)簽,最后添加<element>標(biāo)簽,否則的話會出現(xiàn)如下錯誤:
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.關(guān)系模型
將配置好的對象模型轉(zhuǎn)化為相應(yīng)的關(guān)系模型,生成的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)
生成的對應(yīng)的數(shù)據(jù)庫視圖如下:
二、數(shù)據(jù)操作
1.數(shù)據(jù)寫入
寫入數(shù)據(jù)操作,將數(shù)據(jù)寫入時需要注意創(chuàng)建數(shù)據(jù)對象,其中的List、Set、Map需要創(chuàng)建數(shù)據(jù)對象,將數(shù)據(jù)對象寫入到數(shù)據(jù)庫中,因為它們?nèi)叨际菍ο蠼涌?,所以需要?chuàng)建一個對象,將對象寫入到數(shù)據(jù)庫中,具體代碼如下:
@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.加載數(shù)據(jù)
加載數(shù)據(jù)的方法很簡單,它會將表中的數(shù)據(jù)按照集合加載到對象中,然后只需要獲取相應(yīng)的對象集合即可。
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); } }
生成的結(jié)果:
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]
三、總結(jié)
Hibernate可以持久化以下java集合的實例, 包括java.util.Map, java.util.Set, java.util.SortedMap, java.util.SortedSet, java.util.List, 和任何持久實體或值的數(shù)組(使用Set集合類型是最好的選擇)。類型為java.util.Collection或者java.util.List的屬性還可以使用"bag"語義來持久。用于持久化的集合,除了集合接口外,不能保留任何實現(xiàn)這些接口的類所附加的語義(例如:LinkedHashSet帶來的迭代順序)。所有的持久化集合,實際上都各自按照 HashMap, HashSet, TreeMap, TreeSet 和 ArrayList 的語義直接工作。更深入地說,對于一個包含集合的屬性來說,必須把Java類型定義為接口 (也就是Map, Set 或者List等),而絕不能是HashMap, TreeSet 或者 ArrayList。存在這個限制的原因是,在你不知道的時候,Hibernate暗中把你的Map, Set 和 List 的實例替換成了它自己的關(guān)于Map, Set 或者 List 的實現(xiàn)。(所以在你的程序中,謹(jǐn)慎使用==操作符。)(說明: 為了提高性能等方面的原因,在Hibernate中實現(xiàn)了幾乎所有的Java集合的接口(為了實現(xiàn)懶加載的一些特性) 。)所有的有序集合類(maps, lists, arrays)都擁有一個由<key> 和 <index> 組成的主鍵。 這種情況下集合類的更新是非常高效的——主鍵已經(jīng)被有效的索引,因此當(dāng)Hibernate試圖更新或刪除一行時,可以迅速找到該行數(shù)據(jù)。集合(sets)的主鍵由<key> 和其他元素字段構(gòu)成。 對于有些元素類型來說,這很低效,特別是組合元素或者大文本、大二進(jìn)制字段; 數(shù)據(jù)庫可能無法有效的對復(fù)雜的主鍵進(jìn)行索引。 另一方面,對于一對多、多對多關(guān)聯(lián),特別是合成的標(biāo)識符來說,集合也可以達(dá)到同樣的高效性能。( 附注:如果你希望SchemaExport 為你的<set> 創(chuàng)建主鍵, 你必須把所有的字段都聲明為not-null="true" 。)<idbag> 映射定義了代理鍵,因此它總是可以很高效的被更新。事實上, <idbag> 擁有著最好的性能表現(xiàn)。Bag是最差的。因為bag允許重復(fù)的元素值 ,也沒有索引字段,因此不可能定義主鍵。 Hibernate無法判斷出重復(fù)的行。當(dāng)這種集合被更改時,Hibernate將會先完整地移除 (通過一個(in a single DELETE ))整個集合,然后再重新創(chuàng)建整個集合。 因此Bag是非常低效的。
相關(guān)文章
JAVA演示阿里云圖像識別API,印刷文字識別-營業(yè)執(zhí)照識別
最近有由于工作需要,開始接觸阿里云的云市場的印刷文字識別API-營業(yè)執(zhí)照識別這里我加上了官網(wǎng)的申請說明,只要你有阿里云賬號就可以用,前500次是免費的,API說明很簡陋,只能做個簡單參考2019-05-05MyBatis-Plus中SimpleQuery查詢實現(xiàn)
本文主要介紹了MyBatis-Plus中SimpleQuery查詢實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08解決IDEA集成Docker插件后出現(xiàn)日志亂碼的問題
這篇文章主要介紹了解決IDEA集成Docker插件后出現(xiàn)日志亂碼的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11SpringBoot詳解如果通過@Value注解給靜態(tài)變量注入值
這篇文章主要介紹了springboot如何通過@Value給靜態(tài)變量注入值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06SpringBoot整合Groovy腳本實現(xiàn)動態(tài)編程詳解
這篇文章主要為大家介紹了SpringBoot整合Groovy腳本實現(xiàn)動態(tài)編程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Java后端對接微信支付(小程序、APP、PC端掃碼)包含查單退款
微信支付我們主要聚焦于這三種支付方式,其中JSPAI與APP主要與uniapp開發(fā)微信小程序與APP對接,本文主要介紹了Java后端對接微信支付(小程序、APP、PC端掃碼)包含查單退款,具有一定的參考價值,感興趣的可以了解一下2021-12-12