JPA准则查询与Spring Data Pageable的求和

4

我在代码仓库中有一个方法:

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只返回一个结果。


http://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/ 可能会有所帮助。 - user180100
1个回答

6
你可以执行以下操作:
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

int totalRows = ... 之前,您需要添加 TypedQuery<Long>typedQuery = em.createQuery(query);。我运行了这个方法。typedQuery.getResultList().size(); 总是返回1,因为调用了 query.select(builder.sum(root.get(Order_.price))); - JDon
你要求一个可分页的进程,但查询(sum)没有意义,我知道,但我认为你在代码中进行了更改。但是为了不让其他人感到困惑,我会进行更改。 - Manu Zi
当使用query.select(root.get(Order_.price))时它可以工作,但是query.select(builder.sum(root.get(Order_.price)))只返回一个结果。因此,setMaxResults的工作方式不符合我的需求。 - JDon
这让我有点困惑!但是我以为你需要另一种情况下的可分页性。如果只有一个结果,整个可分页性就没有意义了。 - Manu Zi
小心 int totalRows = query.getResultList().size();因为你之后又再次调用了 getResultList(),这会使应用程序变得更慢。 - Luis Manrique

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接