集合映射:set list bag map
<set>元素:可以映射java.util.Set接口的属性,元素没有顺序且不允许重复。
<list>元素:可以映射java.util.List接口的属性,有顺序,需要在集合属性对应的表中用一个额外的索引保存每个元素的位置。
<bag> <idbag>元素:可以映射java.util.Collection接口的属性,元素可重复,但不保存顺序。
<map>元素:可以映射java.util.Map接口的属性,元素以键/值对的形式保存,也是无序的。
<primitive-array> <array>:可以映射数组元素。
<set>元素
private Set<String> hobbies;
<set name=“hobbies” table=“student_hobby”>
<key column=“student_id”/>
<element type=“string” column=“hobby_name” not-null=“true”/>
</set>
<list>元素
private List<String> hobbies;
<list name=“hobbies” table=“student_hobby”>
<key column=“student_id”/>
<list-index column=“posistion”/>
<element type=“string” column=“hobby_name” not-null=“true”/>
</list>
<bag>元素
private Collection<String> hobbies;
<bag name=“hobbies” table=“student_hobby”>
<key column=“student_id”/>
<element type=“string” column=“hobby_name” not-null=“true”/>
</bag>
<map>元素
private Map<Long String> hobbies;
<map name=“hobbies” table=“student_hobby”>
<key column=“student_id”>
<map-key column=“hobby_id” type=“long”/>
<element type=“string” column=“hobby_name” not-null=“true”/>
</map>
集合映射(set, list, array,bag, map)
<set name=”employees” >
<key column=”depart_id”/>
<one-to-many class=”Employee”/>
<!-- <element type="string" column="name"/> -->
<!--
<composite-element class=”YourClass”>
<property name=”prop1”/>
<property name=”prop2”/>
</composite>
-->
</set>
<list name=”employees” >
<key column=”depart_id”/>
<!—表中有单独的整型列表示list-index à
<list-index column=”order_column”/>
<one-to-many class=”Employee”/>
</list>
<array name=”employees” >
<key column=”depart_id”/>
<!—表中有单独的整型列表示list-index
<list-index column=”order_column”/>
<one-to-many class=”Employee”/>
</array>
<bag name="employees " order-by="id desc">
<key column=”depart_id”/>
<one-to-many class=”Employee”/>
</bag>
<map name="employees ">
<key column=”depart_id”/>
<map-key type="string" column="name"/>
<one-to-many class=”Employee”/>
</map>
这些集合类都是Hibernate实现的类和JAVA中的集合类不完全一样,set,list,map分别和JAVA中的Set,List,Map接口对应,bag映射成JAVA的List;这些集合的使用和JAVA集合中对应的接口基本一致;在JAVA的实体类中集合只能定义成接口不能定义成具体类, 因为集合会在运行时被替换成Hibernate的实现。
集合的简单使用原则:大部分情况下用set,需要保证集合中的顺序用list,想用java.util.List又不需要保证顺序用bag。