0

我有这个Java代码:

CriteriaBuilder qb = entityManager.getCriteriaBuilder(); 
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class))); 
cq.where(/*your stuff*/); 
return entityManager.createQuery(cq).getSingleResult();

我想做一个标准查询:

SELECT COUNT(p),pa.nomPays FROM SessionPersonne s JOIN s.personne p , 
p.entreprise e , e.adresse a , a.localite l , l.pays pa , s.session session 
WHERE size(s.passageCollection)  > 0   GROUP BY pa.nomPays

但是如何size(s.passageCollection) > 0处理关键查询?

谢谢。

4

2 回答 2

1

您可以获得 SIZE 以用于 Criteria,如下所示

Expression<Integer> sizeExpr = qb.size(SessionPersonne_.passageCollection)

因此

qb.greaterThan(sizeExpr, 0);
于 2016-04-12T12:29:03.307 回答
1

本教程很好地解释了一切。 http://www.baeldung.com/jpa-pagination

以防万一链接中断,我将添加一个段并添加应该放置的位置

int pageNumber = 1;
int pageSize = 10;
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
countQuery.select(criteriaBuilder.count(countQuery.from(Foo.class)));
Long count = entityManager.createQuery(countQuery).getSingleResult();

CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
Root<Foo> from = criteriaQuery.from(Foo.class);
CriteriaQuery<Foo> select = criteriaQuery.select(from);
select.where(criteriaBuilder.equal(fromRoot.get("entityColumb"), "bar")));

TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
while (pageNumber < count.intValue()) {
    typedQuery.setFirstResult(pageNumber - 1);
    typedQuery.setMaxResults(pageSize);
    System.out.println("Current page: " + typedQuery.getResultList());
    pageNumber += pageSize;
}
于 2018-04-30T19:59:08.990 回答