从Hibernate的reference中摘抄了几个父子关系映射的实例以及Bag,Set等的实例,贴出来做个记号
一个一个来看一下Hibernate里面提供的几种集合映射的特点以及例子:
- Set节点:A persistent wrapper for a java.util.Set. The underlying collection is a HashSet,直接包装了java的Set类型,Set的特点的话,jdk的文档是这样说的:
一个不包含重复元素的 collection。更正式地说,set 不包含满足 e1.equals(e2) 的元素对 e1 和 e2,并且最多包含一个 null 元素
总结:如果没有使用"sort"属性,则默认使用的是类似于java.util.HashSet的无序的,不允许重复的
/**
* 顾客
* @author Atomic
*/
public class Customer implements Serializable {
public Customer() {
}
Set orders;//顾客所有的订单,这里声明类型一定要是接口,而不能直接声明层HashSet这种具体类型
public Set getOrders() {
return orders;
}
public void setOrders(Set orders) {
this.orders = orders;
}
}
对应的映射代码:
<!-- name:对应的Java属性名 inverse:将控制端交给"多"的一方 sort:指定了的话就可以进行排序,默认值是unsorted,即不排,也可以指定自己的实现了Comparetor的排序器 where:对应的过滤条件将会被附加到sql上 key:描述关系中的外键 column:对应的表中的外键 not-null:是否有非空约束 one-to-many:一对多关系映射到的类 --> <set name="orders" inverse="true" sort="unsorted" where="customerId='Atomic'"> <key column="customerId" not-null="true" /> <one-to-many class="epet.test.Order"/> </set>
- Array节点:A persistent wrapper for an array. Lazy initialization is NOT supported. Use of Hibernate arrays is not really recommended
总结:Array节点直接包装了"数组"这个类型,访问效率应该最高,但是不支持延迟加载,项目中没有映射过,不知道效果如何?
- Bag节点:An unordered, unkeyed collection that can contain the same element multiple times,无序的,允许重复元素的类型
<!-- 使用bag的话可以直接映射成List --> <bag name="orders" inverse="true"> <key column="customerId" not-null="true"/> <one-to-many class="com.gxaccp.epet.test.Order"/> </bag>
- IdBag节点:An IdentifierBag implements "bag" semantics more efficiently than a regular Bag by adding a synthetic identifier column to the table,idbag比bag更加高效,因为他使用了标示符来提高效率,而这个标示符是不用用户干预的
<!-- collection-id:做为关联表用来标示每一行 generator:生成器,可以使用uuid 其余的和普通的manyToMany是一样的 --> <idbag name="roles"> <collection-id type="string" column="id"> <generator class="uuid.hex"/> </collection-id> <key column="customerId" not-null="true"/> <many-to-many class="com.gxaccp.epet.test.Role" column="roleId"/> </idbag>
- List节点: A persistent wrapper for a java.util.List. Underlying collection is an ArrayList.list直接包装了java里的ArrayList,当然,也就有所有List的特点:线性有序的,也可以出现重复元素
<!-- list-index:指定list中的项的排序索引 base:索引从多少开始 composite-element:直接将订单项配进来而不使用额外的class节点 --> <list name="lineItems" inverse="true"> <key column="orderId"/> <list-index column="line_number" base="0"/> <composite-element class="OrderLineItem"> <property name="quantity"/> <many-to-one name="product" class="com.gxaccp.epet.test.Product" column="productId"/> </composite-element> </list>
- Map节点: A persistent wrapper for a java.util.Map. Underlying collection is a HashMap.map直接包装了java里的HashMap,当然,如果指定了sort也可以切换成其他的类型:无序的,键值对的