public Page<T> findPage(final Page<T> page, final String hql, final Object... values) { Assert.notNull(page, "page不能为空"); String newHql = createHqlAddOrderBy(hql, page); Query q = createQuery(newHql, values); if (page.isAutoCount()) { int pageNo = page.getPageNo(); int pageSize = page.getPageSize(); long totalCount = countHqlResult(newHql, values); long z = totalCount / pageSize; long y = totalCount % pageSize; long c = pageNo - z; page.setTotalCount(totalCount); if (y == 0 && c == 1) { // 该页没有数据转到上一页 page.setPageNo(Integer.valueOf(pageNo - 1)); } } setPageParameter(q, page); List result = q.list(); page.setResult(result); return page; }
/** * 按Criterion分页查询. * * @param page 分页参数.包括pageSize、firstResult、orderBy、asc、autoCount. 其中firstResult可直接指定,也可以指定pageNo. * autoCount指定是否动态获取总结果数. * @param criterion 数量可变的Criterion. * @return 分页查询结果.附带结果列表及所有查询时的参数. */ public Page<T> findByCriteria(Page page, Criterion... criterion) { Assert.notNull(page); Criteria c = createCriteria(criterion); if (page.isAutoCount()) { page.setTotalCount(countQueryResult(page, c)); } if (page.isOrderBySetted()) { if (page.getOrder().endsWith("asc")) { c.addOrder(Order.asc(page.getOrderBy())); } else { c.addOrder(Order.desc(page.getOrderBy())); } } // hibernate的firstResult的序号从0开始 c.setFirstResult(page.getFirst() - 1); c.setMaxResults(page.getPageSize()); page.setResult(c.list()); return page; }