`

hibernate 集合类(Collections)映射

阅读更多

 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是非常低效的。

 一、Set集合映射

我的前几篇文章,many-to-many, many-to-one中都用的是Set集合映射,在此不再累述。

  当实体类中有HashSet属性时,它是如何进行初始化的呢?当持久化这个实体类的一个实例,比如调用persist()方法进行了持久化 时,hibernate将自动利用hibernate自己实现了Set接口的类替换掉HashSet。所以一定要防止出现如下所示的错误:

HashSet<Employee> hSet = (HashSet<Employee>)depart.getEmps(); //Error

 当运行时,会出现如下的异常:

java.lang.ClassCastException: org.hibernate.collection.PersistentSet cannot be cast to java.util.HashSet

二、List集合映射

1. 实体类:

实体类还是采用Department和Employee,详见我写的多对一(many-to-one)文章,在它们的基础上进行修改如下所示:

将原Department实体类中的Set替换成List,如下所示:

package com.reiyen.hibernate.domain;

public class Department {

	private int id;
	private String name;
	private List<Employee> emps;
       //Setter和Getter方法
}

在原Employee实体类中增加了重写的toString()方法,方法如下:

@Override
	public String toString() {
		return "id=" + this.id + " name=" + this.name;
	}

 2. 配置文件:

修改Department.hbm.xml配置文件,其它的还是保持以前的不变,修改的Department.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 package="com.reiyen.hibernate.domain">
	<class name="Department" >
		<id name="id" >
			<generator class="native" />
		</id>
		<property name="name" />
		<!--  
		<set name="emps">
		<key column="depart_id" />
		<one-to-many class="Employee"/>
		</set>-->
		<list name="emps">
		<key column="depart_id" />
		<!-- list-index:用来记录加入list集合的元素的顺序 ,会一定程度影响性能,所以可以使用bag替代list-->
		<list-index column="order_col" />
		<one-to-many class="Employee"/>
		</list>
	</class>
</hibernate-mapping>

 3.测试类(只是对many-to-one中的测试类进行了少量的修改),如下所示:

public class Many2One {

	public static void main(String[] args) {
		Department depart = add();
		Department department = queryDepart(depart.getId());
	}

	static Department queryDepart(int departId) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			Department depart = (Department) s.get(Department.class, departId);
			System.out.println("emps:" + depart.getEmps());
			tx.commit();
			return depart;
		} finally {
			if (s != null)
				s.close();
		}
	}

	static Department add() {
		Session s = null;
		Transaction tx = null;
		try {
			Department depart = new Department();
			depart.setName("department name");
			
			Employee employee1 = new Employee();
			employee1.setName("employee1 name1");
			
			Employee employee2 = new Employee();
			employee2.setName("employee2 name2");
			
			List<Employee> list= new ArrayList<Employee>();
			list.add(employee1); //1
			list.add(employee2); //2
			depart.setEmps(list);
			
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(depart);
			s.save(employee1);
			s.save(employee2);
			tx.commit();
			return depart;
		} finally {
			if (s != null)
				s.close();
		}
	}
}

 执行测试类,控制台打印如下信息:

emps:[id=1 name=employee1 name1, id=2 name=employee2 name2]

将测试类中注释为1和注释为2的语句对换顺序后,重新执行,控制台打印如下信息:

emps:[id=2 name=employee2 name2, id=1 name=employee1 name1]

再看数据库表中的记录,如下所示:

mysql> select * from department;
+----+-----------------+
| id | name            |
+----+-----------------+
|  1 | department name |
+----+-----------------+
1 row in set (0.00 sec)

mysql> select * from employee;
+----+-----------------+-----------+-----------+
| id | name            | depart_id | order_col |
+----+-----------------+-----------+-----------+
|  1 | employee1 name1 |         1 |         1 |
|  2 | employee2 name2 |         1 |         0 |
+----+-----------------+-----------+-----------+
2 rows in set (0.00 sec)

说明使用List时,因为配置文件下增加了<list-index column="order_col" />对加入List集合的元素的顺序进行记录,测试结果表明,确实对加入顺序进行了记录。

 

三、bag集合映射(使用bag集合映射时,注意实体类中还是使用java.util.List与之对应)

   如果在实体类中使用了List类型的属性,而我们并不希望保证集合中元素的顺序(保证集合中元素的顺序会采用排序算法,因而会占用一些CPU资源,一定程序上影响性能),可以在配置文件中使用<bag>,它的使用与<list>唯一不同的就是不保证集合中元素的顺序。

在List集合映射的基础上,只需将配置文件中list部分替换成bag即可,其余部分不用修改,Department.hbm.xml配置文件修改如下:

<bag name="emps">
		<key column="depart_id" />
		<one-to-many class="Employee"/>
		</bag>

将测试类中注释为1和注释为2的语句对换顺序后执行,控制台打印如下信息:

emps:[id=1 name=employee1 name1, id=2 name=employee2 name2]

说明已经不再保证它的元素加入的顺序了。

再看数据库表中的记录,如下所示:

 mysql> select * from department;
+----+-----------------+
| id | name            |
+----+-----------------+
|  1 | department name |
+----+-----------------+
1 row in set (0.00 sec)

mysql> select * from employee;
+----+-----------------+-----------+
| id | name            | depart_id |
+----+-----------------+-----------+
|  1 | employee1 name1 |         1 |
|  2 | employee2 name2 |         1 |
+----+-----------------+-----------+
2 rows in set (0.00 sec)

此时数据库就少了记录顺序的那一列值了。

 

四、Map集合映射

Map集合属性不仅需要映射属性value,还需要映射属性key。这里假设Employee的name属性是唯一的,如下修改Employee.hbm.xml配置文件中的name属性,设置unique='true':

<property name="name" unique="true"/>

 实体类Department如下:

public class Department {

	private int id;
	private String name;
	private  Map<String, Employee> emps;
//setter和getter方法

}

 修改Department.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 package="com.reiyen.hibernate.domain">
	<class name="Department">
		<id name="id">
			<generator class="native" />
		</id>
		<property name="name" />
		<map name="emps">
			<key column="depart_id" />
			<map-key type="string" column="name" />
			<one-to-many class="Employee" />
		</map>
	</class>
</hibernate-mapping>

 将测试类下如下注释部分(即List部分)替换,改成Map重新进行测试:

//List<Employee> list= new ArrayList<Employee>();
//			list.add(employee2);
//			list.add(employee1);
			Map<String,Employee> emps = new HashMap<String,Employee>();
			emps.put(employee1.getName(), employee1);
			emps.put(employee2.getName(), employee2);
			depart.setEmps(emps);

 测试结果如下:

emps:{employee1 name1 =id=1 name=employee1 name1, employee2 name2 =id=2 name=employee2 name2}(红色标记部分为key部分)

数据库表中记录如下所示(未发生变化):

mysql> select * from department;
+----+-----------------+
| id | name            |
+----+-----------------+
|  1 | department name |
+----+-----------------+
1 row in set (0.00 sec)

mysql> select * from employee;
+----+-----------------+-----------+
| id | name            | depart_id |
+----+-----------------+-----------+
|  1 | employee1 name1 |         1 |
|  2 | employee2 name2 |         1 |
+----+-----------------+-----------+
2 rows in set (0.00 sec)

五、array(数组)映射

将实体类Department修改如下:

private Employee[] emps;

 Department.hbm.xml修改如下:

<array name="emps">
			<key column="depart_id" />
			<list-index column="order_col" />
			<one-to-many class="Employee"/>
			</array>

 测试类修改如下:

Employee[] emps= new Employee[2];
			emps[0] = employee2;
			emps[1] = employee1;
			depart.setEmps(emps);
 
for(int i = 0; i < depart.getEmps().length; i++){
				System.out.println(depart.getEmps()[i]);
			}

 测试结果如下所示,控制台打印结果:

id=2 name=employee2 name2
id=1 name=employee1 name1

数据库表中记录:

mysql> select * from department;
+----+-----------------+
| id | name            |
+----+-----------------+
|  1 | department name |
+----+-----------------+
1 row in set (0.00 sec)

mysql> select * from employee;
+----+-----------------+-----------+-----------+
| id | name            | depart_id | order_col |
+----+-----------------+-----------+-----------+
|  1 | employee1 name1 |         1 |         1 |
|  2 | employee2 name2 |         1 |         0 |
+----+-----------------+-----------+-----------+
2 rows in set (0.00 sec)

总结:

集合映射(set,list,array,bag,map)这些集合类都是Hibernate实现的类和JAVA中的集合不完全一样,set,list,map
分别和JAVA中的Set,List,Map接口对应,bag映射成JAVA的List;这些集合的使用和JAVA集合中对应的接口基本一致;在JAVA的实体类中集合只能定义成接口,不能定义成具体类,因为集合会在运行时被替换成Hibernate的实现。除了Set和Bag之外的所有集合类型都有一个索引(index)字段,这个字段映射到一个数组或者List的索引或者Map的key。Map的索引的类型可以是任何基本类型, 实体类型或者甚至是一个组合类型(但不能是一个集合类型)。数组和list的索引肯定是整型,integer。在Hibernate配置文件中使用 <index>, <index-many-to-many>, <composite-index> 或者<index-many-to-any>等元素来映射索引。集合的简单使用原则:大部分情况下用set,需要保证集合中的顺序时用list,想用java.util.List又不需要保证顺序时用bag.

分享到:
评论

相关推荐

    Hibernate+中文文档

    6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. ...

    Hibernate框架参考文档

    6. 集合类(Collections)映射; 7. 关联关系映射; 8. 组件(Component)映射; 9. 继承映射(Inheritance Mappings); 10. 与对象共事; 11. 事务和并发; 12. 拦截器与事件(Interceptors and events); 13. 批量处理(Batch...

    hibernate3.2中文文档(chm格式)

    6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. ...

    HibernateAPI中文版.chm

    6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. ...

    hibernate - 数据库持久化

    hibernate的知识:持久化类(Persistent Classes)、对象关系数据库映射基础(Basic OR Mapping)、集合类(Collections)映射、关联关系映射、拦截器与事件(Interceptors and events)等。

    Hibernate中文详细学习文档

    6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. ...

    Hibernate 中文 html 帮助文档

    6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. 索引...

    Hibernate_3.2.0_符合Java习惯的关系数据库持久化

    6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. ...

    最全Hibernate 参考文档

    6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. 索引...

    hibernate 体系结构与配置 参考文档(html)

    6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. ...

    Hibernate教程

    7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. 集合元素(Collection elements) 7.2.3. ...

    hibernate 教程

    集合类(Collections)映射 6.1. 持久化集合类(Persistent Collections) 6.2. 映射集合(Mapping a Collection) 6.3. 值集合和多对多关联(Collections of Values and Many-To-Many Associations) 6.4. ...

    Hibernate参考文档

    6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. 索引...

    hibernate3.04中文文档.chm

    7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. 集合元素(Collection elements) 7.2.3. ...

    Hibernate3的帮助文档

    7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. 集合元素(Collection elements) 7.2.3. ...

    Hibernate3+中文参考文档

    6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. 索引...

    hibernate 框架详解

    7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. 集合元素(Collection elements) 7.2.3...

    hibernate

    集合类(Collections)映射 6.1. 持久化集合类(Persistent Collections) 6.2. 映射集合(Mapping a Collection) 6.3. 值集合和多对多关联(Collections of Values and Many-To-Many Associations) 6.4. ...

    Hibernate中文API大全

    8.2. 在集合中出现的依赖对象 (Collections of dependent objects) Hibernate支持组件的集合(例如: 一个元素是姓名(Name)这种类型的数组)。 你可以使用标签替代标签来定义你的组件集合。 ; ...

    NHibernate中文文档

    第5章 集合类(Collections)映射 13 持久化集合类(Persistent Collections) 13 映射集合(Mapping a Collection) 13 值集合和多对多关联(Collections of Values and Many-To-Many Associations) 14 一对多关联(One-To-...

Global site tag (gtag.js) - Google Analytics