import java.util.*;import org.apache.log4j.*;
import net.sf.hibernate.*;
import net.sf.hibernate.type.*;public class Paginator {
    private static Logger _logger = Logger.getLogger(Paginator.class);
    //--------------------------------------------------------------------------
    private int pageNo; //page number
    private int maxResults; //results per page
    //--------------------------------------------------------------------------
    private int resultCount; //result count
    private int pageCount; //page count
    private int realPageNo; //real page number(if you exceed the max page number,you will be at the last page)
    //--------------------------------------------------------------------------
    private String queryString; //query string
    private String countQueryString; //query string to get the result count
    //--------------------------------------------------------------------------
    public Paginator() {
        this(10, 1);
    }    /**
     * construct a Paginator object
     * @param maxResults results per page
     * @param pageNo page number
     */
    public Paginator(int maxResults, int pageNo) {
        this.setPageInfo(maxResults, pageNo);
    }    public String toString() {
        return
            "\n------------------------------------------------------------\n" +
            "Paginator:\n" +
            "queryString:      [" + this.queryString.trim() + "]\n" +
            "countQueryString: [" + this.countQueryString + "]\n" +
            "pageNo:      [" + this.pageNo + "]\n" +
            "maxResult:   [" + this.maxResults + "]\n" +
            "resultCount: [" + this.resultCount + "]\n" +
            "pageCount:   [" + this.pageCount + "]\n" +
            "realPageNo:  [" + this.realPageNo +
            "]\n------------------------------------------------------------";
    }    //--------------------------------------------------------------------------
    private static final List _emptyList = Collections.unmodifiableList(new
        ArrayList(0));
    //--------------------------------------------------------------------------
    public List list(String queryString) throws
        HibernateException {
        return this.list(SessionManager.openSession(), queryString, null);
    }    public List list(String queryString,
                     Object value, Type type) throws HibernateException {
        return this.list(SessionManager.openSession(), queryString, new String[] {null}
                         , new Object[] {value}
                         , new Type[] {type});
    }    public List list(String queryString, final String[] names,
                     final Object[] values,
                     final Type[] types) throws HibernateException {
        return this.list(SessionManager.openSession(), queryString, names,
                         values, types);
    }    //--------------------------------------------------------------------------
    /*public*/ List list(Session session, String queryString) throws
        HibernateException {
        return this.list(session, queryString, null);
    }    /*public*/ List list(Session session, String queryString,
                         Object value, Type type) throws HibernateException {
        return this.list(session, queryString, new String[] {null}
                         , new Object[] {value}
                         , new Type[] {type});
    }    /*public*/ List list(Session session, String queryString,
                         final String[] names,
                         final Object[] values,
                         final Type[] types) throws HibernateException {
        final int max = names.length;
        if (max != values.length || max != values.length)
            throw new IllegalArgumentException("illegal argument");        return this.list(session, queryString, new QueryParasSetter() {
            public void setQueryParameters(Query q) {
                if (names.length == 1) {
                    q.setParameter(0, values[0], types[0]);
                }
                else {
                    for (int i = 0; i < max; i++) {
                        q.setParameter(names[i], values[i], types[i]);
                    }
                }
            }
        });
    }    /**
     * perform pagination
     * @param session session to perform database operation
     * @param query your Query object with its parameters unset
     * @param qps QueryParasSetter object to set the parameters of your Query object
     * @return the result List
     * @throws HibernateException
     */
    private List list(Session session, String queryString, QueryParasSetter qps) throws
        HibernateException {
        if (queryString.toLowerCase().indexOf(" fetch ") >= 0) {
            throw new UnsupportedOperationException("FETCH is NOT supported!");
        }        this.queryString = queryString;
        Query query = session.createQuery(queryString);
        //-----------------------------------
        List l = null;        FlushMode fm = session.getFlushMode();
        session.setFlushMode(FlushMode.NEVER);        Transaction tx = null;
        try {
            tx = session.beginTransaction();            Query countQuery = this.createCountQuery(session, queryString);
            if (qps != null)
                qps.setQueryParameters(countQuery);
            this.resultCount = ( (Integer) (countQuery.list().get(0))).intValue();
            //this.resultCount = ( (Integer) (countQuery.iterate().next())).intValue();            if (this.resultCount == 0) {
                this.pageCount = 1;
                this.realPageNo = 0;                l = this._emptyList;
            }
            else {
                query.setMaxResults(this.maxResults);
                //--------------------------------------------------------------
                this.pageCount = this.resultCount / this.maxResults;
                if (this.resultCount % this.maxResults != 0)
                    this.pageCount++;                this.realPageNo = this.pageNo;
                if (this.realPageNo > this.pageCount)
                    this.realPageNo = this.pageCount;                int firstResult = this.maxResults * (this.realPageNo - 1);
                query.setFirstResult(firstResult);
                //--------------------------------------------------------------
                if (qps != null)
                    qps.setQueryParameters(query);
                l = query.list();
            }            tx.commit();
        }
        catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            throw new HibernateException(e.getMessage(), e);
        }
        finally {
            session.setFlushMode(fm);
        }
        return l;
    }   

解决方案 »

  1.   

    //--------------------------------------------------------------------------
        public void setPageInfo(int maxResults, int pageNo) {
            if (maxResults <= 0)
                throw new IllegalArgumentException("maxResults=" + maxResults);
            else if (maxResults > 50) {
                _logger.warn("maxResults=" + maxResults);
                maxResults = 50;
            }        if (pageNo <= 0)
                throw new IllegalArgumentException("pageNo=" + pageNo);
            this.pageNo = pageNo;
            this.maxResults = maxResults;
        }    //--------------------------------------------------------------------------
        public int getResultCount() {
            return resultCount;
        }    public int getPageCount() {
            return pageCount;
        }    public int getRealPageNo() {
            return realPageNo;
        }    public int getMaxResults() {
            return maxResults;
        }    //--------------------------------------------------------------------------
        /**
         * create a Query object to get the result count return by Query q
         * @param q your Query object
         * @return count Query
         * @throws HibernateException
         */
        private Query createCountQuery(Session session, String queryString) throws
            HibernateException {
            if (this._logger.isDebugEnabled())
                this._logger.debug("queryString:[" + queryString + "]");        String oqs = queryString.trim();
            String qs = oqs.toLowerCase();        boolean hasSelect = qs.startsWith("select ");
            int selectEndIndex = 0;
            if (hasSelect) {
                selectEndIndex += "select ".length();
            }
            int fromIndex = qs.indexOf("from ", selectEndIndex);
            if (fromIndex < 0)
                throw new RuntimeException("queryString error!");        String s = oqs.substring(selectEndIndex, fromIndex).trim();
            if (s.length() == 0)
                s = "*";        String fromStr = oqs.substring(fromIndex);
            /*int orderIndex = -1;
                 if ( (orderIndex = fromStr.toLowerCase().indexOf(" order ")) >= 0) {
                fromStr = fromStr.substring(0, orderIndex);
                     }*/        countQueryString = "select count(" + s + ") " + fromStr;
            if (this._logger.isDebugEnabled())
                this._logger.debug("countQueryString:[" + countQueryString + "]");
            Query countQuery = session.createQuery(countQueryString);        return countQuery;
        }
    }interface QueryParasSetter {
        public void setQueryParameters(Query q);
    }
      

  2.   

    好像有点复杂啊,Hibernate不是有分页的API吗?
    Query query = session.createQuery(
                   sql);
               query.setFirstResult(fromindex);
               query.setMaxResults(maxindex);
               List list =  query.list();