实现Hibernate 分页的一段代码

来源:互联网 发布:vm linux系统安装教程 编辑:程序博客网 时间:2024/05/17 01:13
       /**
        * @author 苏显斌
        *
        * 获取指定范围的数据库记录。
        * @param helpctyId
        *            帮助分类唯一标识
        * @param startIndex
        *            开始位置
        * @param endIndex
        *            结束位置
        * @return 帮助明细对象列表
        */
       public HelpDetail[] queryDetails(int startIndex,
                     int endIndex) throws HibernateException, MessageException {
              if (startIndex < 0 || endIndex < 0 || (endIndex - startIndex) < 0)
                     throw new MessageException("记录的起始或结束索引无效!");
 
              Session session = HibernateUtil.currentSession();
              Transaction tx = session.beginTransaction();
 
              List list = null;
              try {
                     Query q = session.createQuery("from HelpDetail as detail");
                     q.setFirstResult(startIndex);
                     q.setMaxResults(endIndex - startIndex);
                     list = q.list();
                     tx.commit();
              } finally {
                     HibernateUtil.closeSession();
              }
             
              if (list == null || list.size() <= 0)
                     return new HelpDetail[0];
             
              HelpDetail details[] = new HelpDetail[list.size()];
              for (int i = 0; i < list.size(); i++) {
                     details[i] = (HelpDetail) list.get(i);
              }
             
              return details;
       }
原创粉丝点击