0

I have this Java code:

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

I would like to do this a criteria query:

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

but how do size(s.passageCollection) > 0 with the critical query ?

Thanks you.

user3114639
  • 1,895
  • 16
  • 42
Michel Lammens
  • 591
  • 1
  • 4
  • 11
  • Why is this tagged as java related? – user3114639 Apr 12 '16 at 10:14
  • because criteriaquery criteriabuilder and java are not ?CriteriaBuilder qb = entityManager.getCriteriaBuilder(); CriteriaQuery cq = qb.createQuery(Long.class); cq.select(qb.count(cq.from(MyEntity.class))); cq.where(/*your stuff*/); return entityManager.createQuery(cq).getSingleResult(); – Michel Lammens Apr 12 '16 at 10:19
  • Please add your java code to your question, it will make it more easy to understand what are you trying to do. – user3114639 Apr 12 '16 at 10:22
  • i want convert the JPA code to the criteriaBuilder i'm add the java code – Michel Lammens Apr 12 '16 at 10:30

2 Answers2

1

You can obtain the SIZE for use in Criteria as follows

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

hence

qb.greaterThan(sizeExpr, 0);
Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
1

This tutorial explains everything very well. http://www.baeldung.com/jpa-pagination

Just in case link breaks i'll add a segment and add where the where should be put too

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;
}
ASH
  • 980
  • 1
  • 9
  • 22