使用 HibernateTemplate 實現分頁查詢 (HibernateCallback介面)

來源:互聯網
上載者:User

 

        HibernateTemplate 只支援 .setMaxResults(int) 方法。
        因此,做 Spring+Hibernate 分頁處理要使用到一個介面 org.springframework.orm.hibernate3.HibernateCallback
來靈活操作資料庫,該介面中有一個未實現的方法 Object doInHibernate (Session session),用以獲得並利用 session 進行操作(自動建立、銷毀)。

以下代碼均參考了 使用 HibernateTemplate 實現分頁查詢 一文。

/** *//**
 * 
 */
package springdao;

import hibernatedao.HibernateSessionFactory;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;



/** *//**
 * 通用 DAO 包
 * @author kiant
 * @version Sep 7, 2008
 */
public class CommomsDAO {
    private static final Log log = LogFactory.getLog(EcOpusDAO.class);
    //獲得會話
    private static HibernateTemplate hibernateTemplate = new HibernateTemplate(HibernateSessionFactory.getSessionFactory());
    
    
    /** *//**
     * 分頁通用方法
     * @param hql  HQL查詢語句
     * @param offset    起始記錄下標
     * @param lengh        讀取記錄數
     * @return            List 結果集
     */
    public static List getListForPage(final String hql, final int offset, final int lengh) {
        log.debug("finding ListForPage");
        try {
            List list = hibernateTemplate.executeFind(new HibernateCallback(){

                public Object doInHibernate(Session session)
                        throws HibernateException, SQLException {
                    List list2 = session.createQuery(hql)
                            .setFirstResult(offset)
                            .setMaxResults(lengh)
                            .list();                    
                    return list2;
                }});
            return list;
        } catch (RuntimeException re) {
            log.error("find ListForPage failed", re);
            throw re;
        }
    }
}

ps.
也可以通過:
        this.getSession();
        this.getHibernateTemplate().getSessionFactory().openSession();
分別擷取 session 進行 createQuery()等操作。
但是這種做法,需要自己去手動關閉session的。所以你需要配置openSessioninview,不推薦使用!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.