简体   繁体   English

JPA Criteria查询与Spring Data Pageable的总和

[英]JPA Criteria query sum with Spring Data Pageable

I have a method in repository: 我在存储库中有一个方法:

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

How to write a method with pageable? 如何用pageable编写方法?

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

I don't know where to call setMaxResult and setFirstResult, because sum returns a single result. 我不知道在哪里调用setMaxResult和setFirstResult,因为sum返回一个结果。

You can do the following: 您可以执行以下操作:

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

That is how we do it, I hope it's help. 这就是我们这样做的方式,我希望它有所帮助。

Further information can be found on: http://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa 更多信息请访问: http//spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM