Ejemplo n.º 1
0
  /**
   * 设置分页参数到Criteria对象,辅助函数.
   *
   * @param c Hibernate Criteria
   * @param pageRequest 分页请求参数
   * @return {@link org.hibernate.Criteria}
   */
  protected Criteria setPageRequestToCriteria(Criteria c, PageRequest pageRequest) {
    Assert.isTrue(pageRequest.getPageSize() > 0, "分页大小必须大于0");

    c.setFirstResult(pageRequest.getOffset());
    c.setMaxResults(pageRequest.getPageSize());

    if (pageRequest.isOrderBySetted()) {
      for (PageRequest.Sort sort : pageRequest.getSort()) {
        Order order = null;
        if (sort.getDir().equals(PageRequest.Sort.ASC)) {
          order = Order.asc(sort.getProperty());
        } else {
          order = Order.desc(sort.getProperty());
        }
        c.addOrder(order);
      }
    }

    return c;
  }
Ejemplo n.º 2
0
  /**
   * 根据分页请求参数与Query获取分页请求对象
   *
   * @param request 分页请求参数对象
   * @param query Hibernate Query
   * @return {@link Page}
   */
  public <X> Page<X> findPage(PageRequest request, Query query) {
    Page<X> page = new Page<X>(request);

    if (request == null) {
      return page;
    }

    AbstractQueryImpl impl = (AbstractQueryImpl) query;

    String queryString = setPageRequestToHql(impl.getQueryString(), request);
    ReflectionUtils.setFieldValue(impl, "queryString", queryString);

    if (request.isCountTotal()) {
      long totalCount = 0;

      if (impl.hasNamedParameters()) {
        Map<String, TypedValue> map = ReflectionUtils.getFieldValue(impl, "namedParameters");
        Map<String, Object> values = new HashMap<String, Object>();

        for (Map.Entry<String, TypedValue> entry : map.entrySet()) {
          values.put(entry.getKey(), entry.getValue().getValue());
        }

        totalCount = countHqlResult(impl.getQueryString(), values);

      } else {
        List<Object> values = ReflectionUtils.invokeGetter(impl, "values");
        totalCount = countHqlResult(impl.getQueryString(), values.toArray());
      }

      page.setTotalItems(totalCount);
    }

    impl.setFirstResult(request.getOffset());
    impl.setMaxResults(request.getPageSize());

    List result = impl.list();
    page.setResult(result);

    return page;
  }