使用 HibernateTemplate 实现分页查询

使用 HibernateTemplate 实现分页查询 (HibernateCallback接口)


        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;
         }
     }
}


如果需要为hql语句传入一个参数值:
通过.setParameter(0,value);
如果需要为hql语句传入一个参数组:
通过if(int i =0;i<values.length;i++){
Query.setParameter(i,values[i]);
}
ps.
也可以通过:
        this.getSession();
        this.getHibernateTemplate().getSessionFactory().openSession();
分别获取 session 进行 createQuery()等操作。
但是这种做法,需要自己去手动关闭session的。所以你需要配置openSessioninview,不推荐使用!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值