攻城狮在路上(壹) Hibernate(十)--- 映射值类型集合

一、映射Set(集):未排序,无重复。
  实例代码

<set name="images" table="IMAGES" lazy="true" >
  <key column="CUSTOMER_ID" />
  <element column="FILENAME" type="string" not-null="true"/>
</set> 

  参数说明
name:指定属性名。
table:指定与属性名对应的表名。
lazy:是否延迟加载。
<key>:指定IMAGES的外键。
<element>:指定和images集合中元素对应的字段为FILENAME。

二、映射Bag(包):未排序,允许重复。
  Hibernate允许在持久化类中用List来模拟Bag的行为。
  实例代码

<idbag name="images" table="IMAGES" lazy="true">
  <collection-id type="long" column="ID">
    <generator class="increment"/>
  </collection-id>
  <key column="CUSTOMER_ID" />
  <element column="FILENAME" type="string" not-null="true"/>
</idbag> 

  参数说明
<collection-id>:用于设置IMAGES表的ID主键。

三、映射List(列表):排序,允许重复。
  应该首先在IMAGES表中定义一个POSITION字段,代表每个元素在集合中的索引位置。
  实例代码

<list name="images" table="IMAGES" lazy="true">
  <key column="CUSTOMER_ID" />
  <list-index column="POSITION" />
  <element column="FILENAME" type="string" not-null="true"/>
</list> 

  参数说明
<list-index>:用于设置哪个字段作为索引排序的依据。

四、映射Map
  实例代码

<map name="images" table="IMAGES" lazy="true">
  <key column="CUSTOMER_ID" />
  <map-key column="IMAGE_NAME" type="string"/>
  <element column="FILENAME" type="string" not-null="true"/>
</map> 

  参数说明
<map-key>:用于设置IMAGES表中的哪个字段作为Java持久化类中Map的键。

五、对集合排序
  Hibernate对集合中的元素支持两种排序方式:
    A、在数据库中排序:通过SQL语句的order by 语句实现。
    B、在内存中排序:即当Hibernate把数据库中的集合数据加载到内存中后,利用Java集合的排序功能进行排序。自然排序或者客户化排序两种。
  下面依次说明。
  1、在数据库中对集合排序
  <set>、<idbag>和<map>元素都具有order-by属性,可以通过设置该属性完成,实现原理是在select语句中增加了order by 语句。
  例代码

<set name="images" table="IMAGES" lazy="true" order-by="FILENAME asc">
  <key column="CUSTOMER_ID" />
  <element column="FILENAME" type="string" not-null="true"/>
</set> 

  2、在内存中对集合排序
  <set>和<map>元素都具有sort属性,通过设置该属性对内存中的集合对象进行排序。
  实例代码:集合类型需要实现java.util.SortedSet接口。

<set name="images" table="IMAGES" lazy="true" sort="natural">
  <key column="CUSTOMER_ID" />
  <element column="FILENAME" type="string" not-null="true"/>
</set>

  参数说明

A、natural:说明是进行自然排序。
B、客户化排序:在 sort中指定一个实现了Comparator接口的类的全限定名即可。

六、映射组件类型集合
  实例代码

<set name="images" table="IMAGES" lazy="true" order-by="IMAGE_NAME asc">
  <key column="CUSTOMER_ID" />
  <composite-element class="mypack.Image">
    <parent name="customer" />
    <property name="name" column="IMAGE_NAME" not-null="true" />
    <property name="filename" column="FILENAME" not-null="true" />
    <property name="sizeX" column="SIZEX" not-null="true" />
    <property name="sizeY" column="SIZEY" not-null="true" />
  </composite-element>
</set>



原文地址:https://www.cnblogs.com/tq03/p/3778731.html