五、array(数组)映射
将实体类Department修改如下:
Java代码
private Employee[] emps;
private Employee[] emps; Department.hbm.xml修改如下:
Java代码
<array name="emps">
<key column="depart_id" />
<list-index column="order_col" />
<one-to-many class="Employee"/>
</array>
<array name="emps">
<key column="depart_id" />
<list-index column="order_col" />
<one-to-many class="Employee"/>
</array> 测试类修改如下:
Java代码
Employee[] emps= new Employee[2];
emps[0] = employee2;
emps[1] = employee1;
depart.setEmps(emps);
Employee[] emps= new Employee[2];
emps[0] = employee2;
emps[1] = employee1;
depart.setEmps(emps); Java代码
for(int i = 0; i < depart.getEmps().length; i++){
System.out.println(depart.getEmps()[i]);
}
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.