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

3.類文件
集合映射是如何通過代碼實(shí)現(xiàn)的,接下來具體分析。這里把所有的集合封存到一個(gè)類中,這個(gè)類我們稱之為CollectionMapping.java,那么它對(duì)應(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.集合映射
集合的映射其實(shí)相當(dāng)?shù)暮唵?,只需要添加?duì)應(yīng)的集合標(biāo)簽,Hibernate分別提供了集合標(biāo)簽<set>、<map>、<list>、<array>,通過使用集中標(biāo)簽來將集合映射為對(duì)應(yīng)的關(guān)系表,另外通過添加<key>標(biāo)簽來實(shí)現(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)的對(duì)象是有順序的,所以在添加映射標(biāo)簽時(shí)需要使用list-index或者index標(biāo)簽來標(biāo)明對(duì)象的順序,而且在添加子標(biāo)簽時(shí)一定要按照順序添加,也就是說先添加<key>標(biāo)簽,后添加<list-index>標(biāo)簽,最后添加<element>標(biāo)簽,否則的話會(huì)出現(xiàn)如下錯(cuò)誤:
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)系模型
將配置好的對(duì)象模型轉(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)
生成的對(duì)應(yīng)的數(shù)據(jù)庫視圖如下:


二、數(shù)據(jù)操作
1.數(shù)據(jù)寫入
寫入數(shù)據(jù)操作,將數(shù)據(jù)寫入時(shí)需要注意創(chuàng)建數(shù)據(jù)對(duì)象,其中的List、Set、Map需要?jiǎng)?chuàng)建數(shù)據(jù)對(duì)象,將數(shù)據(jù)對(duì)象寫入到數(shù)據(jù)庫中,因?yàn)樗鼈內(nèi)叨际菍?duì)象接口,所以需要?jiǎng)?chuàng)建一個(gè)對(duì)象,將對(duì)象寫入到數(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ù)的方法很簡單,它會(huì)將表中的數(shù)據(jù)按照集合加載到對(duì)象中,然后只需要獲取相應(yīng)的對(duì)象集合即可。
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集合的實(shí)例, 包括java.util.Map, java.util.Set, java.util.SortedMap, java.util.SortedSet, java.util.List, 和任何持久實(shí)體或值的數(shù)組(使用Set集合類型是最好的選擇)。類型為java.util.Collection或者java.util.List的屬性還可以使用"bag"語義來持久。用于持久化的集合,除了集合接口外,不能保留任何實(shí)現(xiàn)這些接口的類所附加的語義(例如:LinkedHashSet帶來的迭代順序)。所有的持久化集合,實(shí)際上都各自按照 HashMap, HashSet, TreeMap, TreeSet 和 ArrayList 的語義直接工作。更深入地說,對(duì)于一個(gè)包含集合的屬性來說,必須把Java類型定義為接口 (也就是Map, Set 或者List等),而絕不能是HashMap, TreeSet 或者 ArrayList。存在這個(gè)限制的原因是,在你不知道的時(shí)候,Hibernate暗中把你的Map, Set 和 List 的實(shí)例替換成了它自己的關(guān)于Map, Set 或者 List 的實(shí)現(xiàn)。(所以在你的程序中,謹(jǐn)慎使用==操作符。)(說明: 為了提高性能等方面的原因,在Hibernate中實(shí)現(xiàn)了幾乎所有的Java集合的接口(為了實(shí)現(xiàn)懶加載的一些特性) 。)所有的有序集合類(maps, lists, arrays)都擁有一個(gè)由<key> 和 <index> 組成的主鍵。 這種情況下集合類的更新是非常高效的——主鍵已經(jīng)被有效的索引,因此當(dāng)Hibernate試圖更新或刪除一行時(shí),可以迅速找到該行數(shù)據(jù)。集合(sets)的主鍵由<key> 和其他元素字段構(gòu)成。 對(duì)于有些元素類型來說,這很低效,特別是組合元素或者大文本、大二進(jìn)制字段; 數(shù)據(jù)庫可能無法有效的對(duì)復(fù)雜的主鍵進(jìn)行索引。 另一方面,對(duì)于一對(duì)多、多對(duì)多關(guān)聯(lián),特別是合成的標(biāo)識(shí)符來說,集合也可以達(dá)到同樣的高效性能。( 附注:如果你希望SchemaExport 為你的<set> 創(chuàng)建主鍵, 你必須把所有的字段都聲明為not-null="true" 。)<idbag> 映射定義了代理鍵,因此它總是可以很高效的被更新。事實(shí)上, <idbag> 擁有著最好的性能表現(xiàn)。Bag是最差的。因?yàn)閎ag允許重復(fù)的元素值 ,也沒有索引字段,因此不可能定義主鍵。 Hibernate無法判斷出重復(fù)的行。當(dāng)這種集合被更改時(shí),Hibernate將會(huì)先完整地移除 (通過一個(gè)(in a single DELETE ))整個(gè)集合,然后再重新創(chuàng)建整個(gè)集合。 因此Bag是非常低效的。
相關(guān)文章
IDEA中實(shí)現(xiàn)springboot熱部署方式
在IDEA中實(shí)現(xiàn)SpringBoot的熱部署可以通過修改設(shè)置來完成,首先在設(shè)置中搜索Compiler,并勾選Build project automatically,然后進(jìn)入Advanced Settings,勾選Allow auto-make to start even if developed application is currently running2024-09-09
mybatis3使用@Select等注解實(shí)現(xiàn)增刪改查操作
這篇文章主要介紹了mybatis3使用@Select等注解實(shí)現(xiàn)增刪改查操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-11-11
SpringBoot中的@CacheEvict 注解的實(shí)現(xiàn)
本文主要介紹了SpringBoot中的@CacheEvict注解的實(shí)現(xiàn),@CacheEvict 注解用于清空緩存,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-03-03
java 文件目錄讀寫刪除操作詳細(xì)實(shí)現(xiàn)代碼
這篇文章主要介紹了java 文件讀寫刪操作詳細(xì)實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-09-09
Java實(shí)現(xiàn)國產(chǎn)加密算法SM4的示例詳解
這篇文章主要為大家詳細(xì)介紹了Java如何實(shí)現(xiàn)國產(chǎn)加密算法SM4(ECB和CBC兩種模式),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-01-01
使用jenkins+maven+git發(fā)布jar包過程詳解
這篇文章主要介紹了使用jenkins+maven+git發(fā)布jar包過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
詳解Spring/Spring boot異步任務(wù)編程WebAsyncTask
這篇文章主要介紹了詳解Spring/Spring boot異步任務(wù)編程WebAsyncTask,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-06-06

