Spring 整合 Hibernate 时候用的 HibernateTemplate 不支持分页,因此需要自己包装一个类进行分页,具体实现如下...使用spring的hibernateTemplate的回调机制扩展hibernateTemplate的功能实现分页
- /**
- * 使用hql 语句进行操作
- * @param hql
- * @param offset
- * @param length
- * @return List
- */
- public List getListForPage(final String hql, final int offset,
- final int length) {
- List list = getHibernateTemplate().executeFind(new HibernateCallback() {
- public Object doInHibernate(Session session)
- throws HibernateException, SQLException {
- Query query = session.createQuery(hql);
- query.setFirstResult(offset);
- query.setMaxResults(length);
- List list = query.list();
- return list;
- }
- });
- return list;
- }/**
- * 使用criterion进行操作
- * @param arg
- * @param criterions
- * @param offset
- * @param length
- * @return List
- */
- protected List getListForPage(final Class arg, final Criterion[] criterions,final int offset, final int length) {
- List list = getHibernateTemplate().executeFind(new HibernateCallback() {
- public Object doInHibernate(Session session)
- throws HibernateException, SQLException {
- Criteria criteria = session.createCriteria(arg);
- //循环遍历添加约束条件
- for (int i = 0; i < criterions.length; i++) {
- criteria.add(criterions[i]);
- }
- criteria.setFirstResult(offset);
- criteria.setMaxResults(length);
- return criteria.list();
- }
- });
- return list;
- }
- // 获得集合的总数(聚合查询)
- public Integer getSaleChanceListCount() {
- final String hql = "select count(*) from SaleChanceInfo si";
- Integer result = null;
- result = (Integer)getHibernateTemplate().execute(new HibernateCallback() {
- public Object doInHibernate(Session arg0)
- throws HibernateException, SQLException {
- Query query = arg0.createQuery(hql);
- return query.uniqueResult();
- }
- });
- return result;
- }