/** * 使用HQL进行分页查询. * * @param hql 查询条件 * @param pageNo 页号,从1开始. * @param pageSize 每页中的记录数 * @param args HQL的参数 * @return 当前页的分页对象 */ public Page pagedQuery(String hql, int pageNo, int pageSize, Object... args) { Assert.hasText(hql); // 创建查询 Query query = getSession().createQuery(hql); // 根据华南提出的bug做出修正,做是否为null的判断 if (args != null) { for (int i = 0; i < args.length; i++) { query.setParameter(i, args[i]); } } String countQueryString = " SELECT count (*) " + removeSelect(removeOrders(hql)); List countlist = getHibernateTemplate().find(countQueryString, args); long totalCount = (Long) countlist.get(0); // 返回分页对象 if (totalCount < 1) return new Page(); int startIndex = Page.getStartOfPage(pageNo, pageSize); List list; if (!entityQueryCache.isCached(hql, pageNo, pageSize, args)) { logger.debug("Not Using Cache for query: " + hql); list = query.setFirstResult(startIndex).setMaxResults(pageSize).list(); } else { logger.debug("Using Cache for query: " + hql); list = new ArrayList(); for (Iterator it = query.setFirstResult(startIndex).setMaxResults(pageSize).iterate(); it.hasNext(); ) { list.add(it.next()); } } return new Page(startIndex, totalCount, pageSize, list); }
/** * 使用指定查询对象进行分页查询. * * @param criteria 实体的查询对象 * @param pageNo 页号,从1开始. * @param pageSize 每页中的记录数 * @return 当前页的分页对象 */ public Page pagedQuery(Criteria criteria, int pageNo, int pageSize) { CriteriaImpl impl = (CriteriaImpl) criteria; // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作 Projection projection = impl.getProjection(); List<CriteriaImpl.OrderEntry> orderEntries; try { orderEntries = (List) BeanUtils.getPrivateProperty(impl, "orderEntries"); BeanUtils.setPrivateProperty(impl, "orderEntries", new ArrayList()); } catch (Exception e) { logger.error(e.getMessage()); throw new InternalError(" Runtime Exception impossibility throw "); } // 执行查询 long totalCount = ((Number) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue(); // 将之前的Projection和OrderBy条件重新设回去 criteria.setProjection(projection); if (projection == null) { criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } try { BeanUtils.setPrivateProperty(impl, "orderEntries", orderEntries); } catch (Exception e) { logger.error(e.getMessage()); throw new InternalError(" Runtime Exception impossibility throw "); } // 返回分页对象 if (totalCount < 1) return new Page(); int startIndex = Page.getStartOfPage(pageNo, pageSize); List list = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list(); return new Page(startIndex, totalCount, pageSize, list); }