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>元素的排序属性

排 序 属 性


[img]http://dl.iteye.com/upload/attachment/463794/4bc0660f-4a17-3c29-b4e4-15de7cde08de.png[/img]


从表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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值