文档条目的排序

来源:互联网 发布:数据走势图怎么做 编辑:程序博客网 时间:2024/05/25 19:57

       在项目中,对文档条目的排序十分常见,如招聘网站在搜索  xxx 关键字后,显示的招聘职位列表。通常可按照创建时间,条目名称,公司名称(可能有),创建者,条目文件大小等排序。

 

实现功能,办法有很多,一开始,我觉得无非就是多写一些sql语句,根据排序的条件,以及asc或desc 来处理, 然后就所谓的制造出if-else if语句,但是,这样将造成大量重复代码,

   需注意完成是一方面,完成的好坏又是一方面!

  排序,本质上是查询,就是按照一定规则对文件,或条目进行查询,因此排序必然返回结果,通常以List来存储


1首先在DAO接口 写一个方法(假设对文件进行排序)
public List<DocumentItem> listDocumentItemsByDocumentCatalogIdAndCondition(Long documentCatalogId,String condition,String way);
2 在DAOImpl类写实现方法,涉及到hql字符串的拼接
public List<DocumentItem> listDocumentItemsByDocumentCatalogIdAndCondition(Long documentCatalogId,String
condition,String way){

 StringBuffer sb = new StringBuffer();
 sb.append("from DocumentItem bean where bean.documentCatalog.id = ? order by bean.").append(condition)
   .append(" ").append(way);
 String hql = sb.toString();
 List<DocumentItem> list = (List<DocumentItem>)this.getHibernateTemplate()
  .find(hql,documentCatalogId);
 return list;

}
3 在Service,ServiceImpl增加类似代码

4 在action增加两个参数,String condition,String way,//way 只有asc/desc两种选择
 //假如用户没有选择排序,默认按id进行排序
 if(null = condition){
  condition = "id";
  way = "desc";
 }
 this.setList(this.service.listDocumentItemsByDocumentCatalogIdAndCondition(documentCatalogId,condition,way))


5 在jsp页面 假设按名称排序,这里需要升序,降序两个小图片
名称&nbsp;<a hrer="lsitDocumentItem.action?documentCatalogId=<s:property value="documentCatalogId" />&condition=name&way=asc">
<img src="up.gif" alt="升序" border="0" width="11" height="11"></a>
&nbsp;<a hrer="lsitDocumentItem.action?documentCatalogId=<s:property value="documentCatalogId" />&condition=name&way=desc">
<img src="down.gif" alt="降序" border="0" width="11" height="11"></a>

 

 

   

原创粉丝点击