集合映射详解

一、集合映射


  1.1 集合小介


     集合映射也是基本的映射,但在开发过程中不会经常用到,所以不需要深刻了解,只需要理解基本的使用方法即可,等在开发过程中遇到了这种问题时能够查询到解决方法就可以了。对应集合映射它其实是指将java中的集合映射到对应的表中,是一种集合对象的映射,在java中有四种类型的集合,分别是Set、Map、List还有普通的数组,它们之间有很大的区别:

       Set,不可以有重复的对象,对象是无序的;

       List,可以与重复的对象,对象之间有顺序;

       Map,它是键值成对出现的;

       数组,可以重复,对象之间有顺序。

       它们之间的区别决定了在开发时使用哪种集合,通常在开发时会使用Set,它内部的对象是无需的,并可以使用迭代器获取内部对象。这几种集合想要映射到相应的关系模型的话就必须使用Hibernate提供的映射标签,<set>、<list>、<map>、<array>。


   1.2 映射小介


        继续讨论集合映射的关系模型,集合映射是指一个对象对应着另一个对象集合,在保存时Hibernate会把数据集合保存到相应的表中,并按照自己分配的id把数据保存到数据表中,如果单独为集合分配了新表,那么会将id分配给集合表的id,那么对应的关系表如下图:


  1.3 类文件


        集合映射是如何通过代码实现的,接下来具体分析。这里把所有的集合封存到一个类中,这个类我们称之为CollectionMapping.java,那么它对应的内部代码如下:在CODE上查看代码片

  1. package com.hibernate;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5. import java.util.Set;  
  6.   
  7. @SuppressWarnings("rawtypes")  
  8. public class CollectionMapping {  
  9.       
  10.     //id  
  11.     private int id;  
  12.     public int getId() {  
  13.         return id;  
  14.     }  
  15.     public void setId(int id) {  
  16.         this.id = id;  
  17.     }  
  18.       
  19.     //名字  
  20.     private String name;  
  21.     public String getName() {  
  22.         return name;  
  23.     }  
  24.     public void setName(String name) {  
  25.         this.name = name;  
  26.     }  
  27.       
  28.     //Set集合  
  29.     private Set setValues;  
  30.     public Set getSetValues() {  
  31.         return setValues;  
  32.     }  
  33.     public void setSetValues(Set setValues) {  
  34.         this.setValues = setValues;  
  35.     }  
  36.       
  37.     //List集合  
  38.     private List listValues;  
  39.     public List getListValues() {  
  40.         return listValues;  
  41.     }  
  42.     public void setListValues(List listValues) {  
  43.         this.listValues = listValues;  
  44.     }  
  45.       
  46.     //数组集合  
  47.     private String[] arrayValues;  
  48.     public String[] getArrayValues() {  
  49.         return arrayValues;  
  50.     }  
  51.     public void setArrayValues(String[] arrayValues) {  
  52.         this.arrayValues = arrayValues;  
  53.     }  
  54.       
  55.     //Map集合  
  56.     private Map mapValues;  
  57.     public Map getMapValues() {  
  58.         return mapValues;  
  59.     }  
  60.     public void setMapValues(Map mapValues) {  
  61.         this.mapValues = mapValues;  
  62.     }  
  63. }  

        该类中封装了几种常用的集合,想要转化为关系模型,就必须来看下文的映射。


  1.4 集合映射


       集合的映射其实相当的简单,只需要添加对应的集合标签,Hibernate分别提供了集合标签<set>、<map>、<list>、<array>,通过使用集中标签来将集合映射为对应的关系表,另外通过添加<key>标签来实现表外键的关联,其它的属性通过使用<element>来添加。

      CollectionMapping.hbm.xml


  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC   
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.     <class name="com.hibernate.CollectionMapping" table="t_collection_mapping">  
  7.         <id name="id">  
  8.             <generator class="native"/>  
  9.         </id>  
  10.         <property name="name"/>  
  11.           
  12.         <set name="setValues" table="t_set_values">  
  13.             <key column="set_id"></key>  
  14.             <element type="string" column="set_value"></element>  
  15.         </set>  
  16.         <list name="listValues" table="t_list_values">  
  17.             <key column="list_id"/>  
  18.             <list-index column="list_index"/>  
  19.             <element type="string" column="list_value"/>  
  20.         </list>  
  21.         <map name="mapValues" table="t_map_values">  
  22.             <key column="map_id"/>  
  23.             <map-key type="string" column="map_key"/>  
  24.             <element type="string" column="map_value"/>  
  25.         </map>  
  26.         <array name="arrayValues" table="t_array_value">  
  27.             <key column="array_id"/>            
  28.             <index column="array_index" type="integer"></index>  
  29.             <element type="string" column="array_value"/>  
  30.         </array>  
  31.     </class>  
  32. </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*)".


  1.5 关系模型


      将配置好的对象模型转化为相应的关系模型,生成的SQL语句如下:


  1. alter table t_array_value drop foreign key FK2E0DD0C067676B68  
  2. alter table t_list_values drop foreign key FKE01EC98BF4FCB03  
  3. alter table t_map_values drop foreign key FKD169BA107402B585  
  4. alter table t_set_values drop foreign key FK7BB8D04A7E79F8BF  
  5. drop table if exists t_array_value  
  6. drop table if exists t_collection_mapping  
  7. drop table if exists t_list_values  
  8. drop table if exists t_map_values  
  9. drop table if exists t_set_values  
  10. create table t_array_value (array_id integer not null, array_value varchar(255), array_index integer not nullprimary key (array_id, array_index))  
  11. create table t_collection_mapping (id integer not null auto_increment, name varchar(255), primary key (id))  
  12. create table t_list_values (list_id integer not null, list_value varchar(255), list_index integer not nullprimary key (list_id, list_index))  
  13. create table t_map_values (map_id integer not null, map_value varchar(255), map_key varchar(255) not nullprimary key (map_id, map_key))  
  14. create table t_set_values (set_id integer not null, set_value varchar(255))  
  15. alter table t_array_value add index FK2E0DD0C067676B68 (array_id), add constraint FK2E0DD0C067676B68 foreign key (array_id) references t_collection_mapping (id)  
  16. alter table t_list_values add index FKE01EC98BF4FCB03 (list_id), add constraint FKE01EC98BF4FCB03 foreign key (list_id) references t_collection_mapping (id)  
  17. alter table t_map_values add index FKD169BA107402B585 (map_id), add constraint FKD169BA107402B585 foreign key (map_id) references t_collection_mapping (id)  
  18. alter table t_set_values add index FK7BB8D04A7E79F8BF (set_id), add constraint FK7BB8D04A7E79F8BF foreign key (set_id) references t_collection_mapping (id)  


     生成的对应的数据库视图如下:
  


二、数据操作


  2.1 数据写入


        写入数据操作,将数据写入时需要注意创建数据对象,其中的List、Set、Map需要创建数据对象,将数据对象写入到数据库中,因为它们三者都是对象接口,所以需要创建一个对象,将对象写入到数据库中,具体代码如下:


  1. @SuppressWarnings({ "unchecked""rawtypes" })  
  2. public void testsave(){  
  3.       
  4.     Session session=null;  
  5.     try{  
  6.         session=HibernateUtils.getSession();  
  7.         session.beginTransaction();  
  8.           
  9.         CollectionMapping cm=new CollectionMapping();  
  10.         cm.setName("zhangsan");  
  11.           
  12.         Set set=new HashSet();  
  13.         set.add("a");  
  14.         set.add("b");  
  15.         cm.setSetValues(set);  
  16.           
  17.         List list=new ArrayList();  
  18.         list.add("list1");  
  19.         list.add("list2");  
  20.         cm.setListValues(list);  
  21.           
  22.         String[] str=new String[]{"array1","array2"};  
  23.         cm.setArrayValues(str);  
  24.           
  25.         Map map=new HashMap();  
  26.         map.put("k1","v1");  
  27.         map.put("k2""v2");  
  28.         cm.setMapValues(map);  
  29.           
  30.         session.save(cm);  
  31.         session.getTransaction().commit();  
  32.     }catch(Exception e){  
  33.         e.printStackTrace();  
  34.         session.getTransaction().rollback();  
  35.     }finally{  
  36.         HibernateUtils.closeSession(session);  
  37.     }  
  38. }  

        生成的SQL语句如下:

  1. Hibernate: insert into t_collection_mapping (name) values (?)  
  2. Hibernate: insert into t_set_values (set_id, set_value) values (?, ?)  
  3. Hibernate: insert into t_set_values (set_id, set_value) values (?, ?)  
  4. Hibernate: insert into t_list_values (list_id, list_index, list_value) values (?, ?, ?)  
  5. Hibernate: insert into t_list_values (list_id, list_index, list_value) values (?, ?, ?)  
  6. Hibernate: insert into t_map_values (map_id, map_key, map_value) values (?, ?, ?)  
  7. Hibernate: insert into t_map_values (map_id, map_key, map_value) values (?, ?, ?)  
  8. Hibernate: insert into t_array_value (array_id, array_index, array_value) values (?, ?, ?)  
  9. Hibernate: insert into t_array_value (array_id, array_index, array_value) values (?, ?, ?)  

  2.2 加载数据


      加载数据的方法很简单,它会将表中的数据按照集合加载到对象中,然后只需要获取相应的对象集合即可。


  1. public void testload(){  
  2.     Session session=null;  
  3.     try{  
  4.         session=HibernateUtils.getSession();  
  5.         session.beginTransaction();  
  6.           
  7.         CollectionMapping cm=(CollectionMapping)session.load(CollectionMapping.class1);  
  8.           
  9.         System.out.println("cm.name= "+cm.getName());  
  10.         System.out.println("cm.list= "+cm.getListValues());  
  11.         System.out.println("cm.map= "+cm.getMapValues());  
  12.         System.out.println("cm.array= "+cm.getArrayValues());  
  13.         System.out.println("cm.set= "+cm.getSetValues());  
  14.           
  15.         session.getTransaction().commit();  
  16.     }catch(Exception e){  
  17.         e.printStackTrace();  
  18.         session.getTransaction().rollback();  
  19.     }finally{  
  20.         HibernateUtils.closeSession(session);  
  21.     }  
  22. }  

      生成的结果:

  1. Hibernate: select collection0_.id as id0_0_, collection0_.name as name0_0_ from t_collection_mapping collection0_ where collection0_.id=?  
  2. 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=?  
  3. cm.name= zhangsan  
  4. 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=?  
  5. cm.list= [list1, list2]  
  6. 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=?  
  7. cm.map= {k1=v1, k2=v2}  
  8. cm.array= [Ljava.lang.String;@758d8478  
  9. Hibernate: select setvalues0_.set_id as set1_0_, setvalues0_.set_value as set2_0_ from t_set_values setvalues0_ where setvalues0_.set_id=?  
  10. cm.set= [b, a]  


结语


       集合映射在开发过程中不会经常用到,但是要做基本的了解,理解这种映射的实现方法,是通过相对应的集合标签来实现的模型转化,很简单。截止到该篇文章,Hibernate基本的映射已经讨论完成,这些映射是对象模型转化为关系模型中经常用到的,文章对映射的用法做了详细的讨论,它们之间的关系还没有做进一步的探讨,所以下篇文章将会对映射做基本的总结展望,对映射进行对比分类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值