2014-11-21 56 views
3

JPA标准查询和我在仓库里的方法:与Spring数据可分页

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

+0

http://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/可能有助于 – 2014-11-21 07:14:56

回答

2

你可以做到以下几点:

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

+0

您需要在'int totalRows = ...'之前添加'TypedQuery typedQuery = em.createQuery(query);''。我运行这个方法。 'typedQuery.getResultList()。size();'总是返回1,因为调用'query.select(builder.sum(root.get(Order_.price)));'。 – JDon 2014-11-21 08:06:46

+0

你问一个可分页的过程,查询(总和)没有意义,我知道,但我的事情你改变它在你的代码。但是,我不会混淆别人,我会改变它。 – 2014-11-21 08:10:38

+0

它适用于使用query.select(root.get(Order_.price)),但query.select(builder.sum(root.get(Order_.price)))返回单个结果。所以setMaxResults不按我的需要工作。 – JDon 2014-11-21 11:15:24