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,不推荐使用! 相关文章: