Hibernate对会合排序

Hibernate对集合排序

Hibernate对集合中的元素支持两种排序方式:

Ø 在数据库中排序:简称为数据库排序,当Hibernate通过select语句到数据库中检索集合对象时,利用order by子句进行排序。

Ø 在内存中排序:简称为内存排序,当Hibernate把数据库中的集合数据加载到内存中的Java集合中后,利用Java集合的排序功能进行排序,可以选择自然排序或者客户化排序两种方式。

在映射文件中,Hibernate用sort属性来设置内存排序,用order-by属性来设置数据库排序,表14-2显示了<set>、<idbag>、<list>和<map>元素的排序属性。

表14-2 <set>、<idbag>、<list>和<map>元素的排序属性

排 序 属 性

<set>

<idbag>

<list>

<map>

sort属性(内存排序)

支持

不支持

不支持

支持

order-by属性(数据库排序)

支持

支持

不支持

支持

从表14-2看出,<set>和<map>元素支持内存排序和数据库排序,<list>元素不支持任何排序方式,而<idbag>仅支持数据库排序。

14.5.1 在数据库中对集合排序

<set>、<idbag>和<map>元素都具有order-by属性,如果设置了该属性,当Hibernate通过select语句到数据库中检索集合对象时,利用order by子句进行排序。

下面对本章14.1节的Customer.hbm.xml文件中的<set>元素增加一个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>  

以上代码表明对images集合中的元素进行升序排列,当Hibernate加载Customer对象的images集合时,执行的select语句为:

select CUSTOMER_ID,FILENAME from IMAGES

where CUSTOMER_ID=1 order by FILENAME;

在DOS命令行下进入chapter14根目录,然后输入命令:

ant -file build1.xml run

就会运行BusinessService类。BusinessService的main()方法调用test()方法,它的输出结果如下:

org.hibernate.collection.PersistentSet

Tom image1.jpg

Tom image2.jpg

Tom image4.jpg

Tom image5.jpg

在order-by属性中还可以加入SQL函数,例如:

<set   name="images"   table="IMAGES"    lazy="true"

order-by="lower(FILENAME) desc">

 

<key column="CUSTOMER_ID" />

         <element column="FILENAME" type="string" not-null="true"/>

</set>  

当Hibernate加载Customer对象的images集合时,执行的select语句为:

select CUSTOMER_ID,FILENAME from IMAGES

where CUSTOMER_ID=1 order by lower(FILENAME) desc;

在<map>元素中也可以加入order-by属性,以下代码表明对Map类型的images集合中的键对象进行排序:

<map   name="images"   table="IMAGES"   lazy="true" order-by="IMAGE_NAME">

        <key column="CUSTOMER_ID" />

        <map-key column="IMAGE_NAME" type="string"/>

        <element column="FILENAME" type="string" not-null="true"/>

</map>  

以下代码表明对Map类型的images集合中的值对象进行排序:

<map   name="images"   table="IMAGES"   lazy="true" order-by="FILENAME">

        <key column="CUSTOMER_ID" />

        <map-key column="IMAGE_NAME" type="string"/>

        <element column="FILENAME" type="string" not-null="true"/>

</map>  

在<idbag>元素中也可以加入order-by属性,以下代码表明按照IMAGES表中的ID代理主键排序:

<idbag   name="images"   table="IMAGES"    lazy="true" order-by="ID">

        <collection-id type="long" column="ID">

           <generator class="increment"/>

        </collection-id>

        <key column="CUSTOMER_ID" />

        <element column="FILENAME" type="string" not-null="true"/>

</idbag>  

http://book.csdn.net/bookfiles/1264/100126437749.shtml