您的位置:首页 > 其它

hibernate 配置Set排序

2009-10-26 11:56 260 查看
hibernate 中对set对象的两种配置方法:

(一)使用order-by对set排序,只需要修改set设置:

<set name="standards" ... order-by="st_id desc"
>

...

</set>

//注意:st_id必须是数据表里的字段名,不能使类里的属性名

//使用order-by,实质是hibernate自动在查询语句后面添加order by ...语句。

(二)使用sort对set排序

1.修改set设置:

<set name="standards" ... sort="mypack.module.AsStandard"
>

...

</set>

注意:

属性standards要定义成:

private Set<AsStandard> standards = new TreeSet
<AsStandard>();

不能定义成HashSet
,否则不能用sort进行排序。

2.修改实体类AsStandard:

public class AsStandard implements Comparator
{ // 1.实现接口Comparator

...

public int compare
(Object o1, Object o2) { // 2.实现方法compare

if(o1 instanceof AsStandard && o2 instanceof AsStandard){

AsStandard r1 = (AsStandard)o1;

AsStandard r2 = (AsStandard)o2;

if(r1.stId>r2.stId){ //stId是类里的属性名,不是数据表里的字段名

return 1;

}

}

return -1;

}

}

//如果支持泛型,可写成:

public class AsStandard implements Comparator<AsStandard>
{ // 1.实现接口Comparator

...

public int compare(AsStandard o1, AsStandard o2
) { // 2.实现方法compare

if(o1.stId>o2.stId){

return -1;

}

return 1;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: