13

maybe it's a silly question but I cannot find the answer in the docs: How can set a limit to the CriteriaQuery using JPA2?

Thanks

Hugo
  • 2,139
  • 4
  • 22
  • 30

3 Answers3

21

A CriteriaQuery is not an executable Query. You need to create a TypedQuery first using EntityManager.createQuery(criteriaQuery). You can then set the max results of this and execute it.

Mike Q
  • 22,839
  • 20
  • 87
  • 129
12

You could define the offset/limit like this:

return em.createQuery(query)
     .setFirstResult(offset) // offset
     .setMaxResults(limit) // limit
     .getResultList();
Raging Bull
  • 18,593
  • 13
  • 50
  • 55
Uttam
  • 121
  • 1
  • 2
0

I usually use:

em.createQuery(criteria).setFirstResult(offset).setMaxResults(max).getResultList();
Oleksii Kyslytsyn
  • 2,458
  • 2
  • 27
  • 43