/** * 向hql中设置orderBy条件(可以处理以有order by的hql和没有order by的hql) * * @param hql hql语句 * @param page 分页和排序参数 * @return */ protected String createHqlAddOrderBy(final String hql, final Page<T> page) { String newHql = hql; if (page.isOrderBySetted()) { String[] orderByArray = StringUtils.split(page.getOrderBy(), ','); String[] orderArray = StringUtils.split(page.getOrder(), ','); Assert.isTrue(orderByArray.length == orderArray.length, "分页多重排序参数中,排序字段与排序方向的个数不相等"); String orderByStr = ""; if (StringUtils.contains(newHql, "order by")) { for (int i = 0; i < orderByArray.length; i++) { if ((i + 1) == orderByArray.length) { orderByStr += getAlias(hql) + "." + orderByArray[i].trim() + " " + orderArray[i].trim(); } else { orderByStr += getAlias(hql) + "." + orderByArray[i].trim() + " " + orderArray[i].trim() + ", "; } } newHql = StringUtils.substringBefore(newHql, "order by") + "order by " + orderByStr; } else { orderByStr = " order by "; for (int i = 0; i < orderByArray.length; i++) { if ((i + 1) == orderByArray.length) { orderByStr += getAlias(hql) + "." + orderByArray[i].trim() + " " + orderArray[i].trim(); } else { orderByStr += getAlias(hql) + "." + orderByArray[i].trim() + " " + orderArray[i].trim() + ", "; } } newHql += orderByStr; } } log.debug("newHql =" + newHql); return newHql; }
/** * 按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; }