JDo*_*Don 4 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();
}
Run Code Online (Sandbox Code Playgroud)
如何用 pageable 编写一个方法?
public Long sumOfPrices(Specification<Order> spec, Pageable pageable)
Run Code Online (Sandbox Code Playgroud)
我不知道在哪里调用 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;
}
Run Code Online (Sandbox Code Playgroud)
我们就是这样做的,希望对您有所帮助。
可以在以下位置找到更多信息:http : //spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa
| 归档时间: |
|
| 查看次数: |
8639 次 |
| 最近记录: |