Hibernate集合映射

本文详细介绍了Hibernate中集合映射的概念,包括set、list、bag、map等不同类型的映射方式及其XML配置示例,帮助读者理解如何在Java实体类中正确使用这些集合。
                                                                                     集合映射: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。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值