zoukankan      html  css  js  c++  java
  • 【Hibernate步步为营】--最后的集合映射

           上篇文章具体讨论了组合对象映射的原理。它事实上指的是怎样将对象模型中的组合关系映射到关系模型中,它是通过使用Hibernate提供的<component>标签来实现的,并须要在该标签中加入相应组合对象的属性,有关组合对象的映射请查看笔者的上篇文章。该篇文章来具体讨论下集合的映射关系。Java的集合有四种各自是Set、Map、List和普通集合,在开发时往往须要将这些集合转化为相应的关系模型,这样的集合映射的实现过程就是我们今天要讨论的话题。


    一、集合映射


      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,那么它相应的内部代码例如以下:

    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;
    	}
    }
    

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


      1.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*)".


      1.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)
    


         生成的相应的数据库视图例如以下:
      


    二、数据操作


      2.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.2 载入数据


          载入数据的方法非常easy。它会将表中的数据依照集合载入到对象中,然后仅仅须要获取对应的对象集合就可以。

    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]



    结语


           集合映射在开发过程中不会经经常使用到,可是要做主要的了解,理解这样的映射的实现方法,是通过相相应的集合标签来实现的模型转化。非常easy。截止到该篇文章。Hibernate主要的映射已经讨论完毕,这些映射是对象模型转化为关系模型中经经常使用到的,文章对映射的使用方法做了具体的讨论,它们之间的关系还没有做进一步的探讨,所下面篇文章将会对映射做主要的总结展望,对映射进行对照分类。




  • 相关阅读:
    linux下清空文件的几种方式以及对比
    远程桌面连接无法验证您希望连接的计算机的身份-mac连接远程桌面
    Linux配置临时IP和网关命令
    linux(centos、ubuntu)网卡配置文件不生效
    负载均衡
    Zookeeper基础使用机制原理
    高性能RPC框架选型
    事务隔离机制
    一致性协议Raft
    机器学习入门
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/7372542.html
Copyright © 2011-2022 走看看