java-具有Spring Data Pageable的JPA Criteria查询总和

我在存储库中有一个方法:

public Long sumOfPrices(Specification<Order> spec) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> query = builder.createQuery(Long.class);
    Root<Order> root = query.from(Order.class);
    query.select(builder.sum(root.get(Order_.price)));
    query.where(spec.toPredicate(root, query, builder));
    return sum = em.createQuery(query).getSingleResult();
}

如何编写可分页的方法?

public Long sumOfPrices(Specification<Order> spec, Pageable pageable)

我不知道在哪里调用setMaxResult和setFirstResult,因为sum返回单个结果.

解决方法:

您可以执行以下操作:

public Page<Long> sumOfPrices(Specification<Order> spec, Pageable pageable) {
    // Your Query
    ...

    // Here you have to count the total size of the result
    int totalRows = query.getResultList().size();

    // Paging you don't want to access all entities of a given query but rather only a page of them      
    // (e.g. page 1 by a page size of 10). Right now this is addressed with two integers that limit 
    // the query appropriately. (http://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa)
    query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
    query.setMaxResults(pageable.getPageSize());

    Page<Long> page = new PageImpl<Long>(query.getResultList(), pageable, totalRows);
    return page;
}

这就是我们的工作方式,希望对您有所帮助.

有关更多信息,请访问:http://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa

上一篇:java-如何在休眠中实现多个内部联接


下一篇:关于mongoDB使用java实现高级查询query参数的组装