JPA Criteria查询与Spring Data Pageable的总和

时间:2014-11-21 07:10:47

标签: java spring jpa criteria spring-data-jpa

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

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();
}

如何用pageable编写方法?

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

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

1 个答案:

答案 0 :(得分:4)

您可以执行以下操作:

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