Aquillo Aquillo - 3 months ago 31
SQL Question

JPA 2 CriteriaQuery, using a limit

I am using JPA 2. For safety reasons, I am working type safe with CriteriaQuery's (and thus, I am not searching for any solutions of typed queries and so on).
I have recently come across an issue in which I need to set a SQL-LIMIT.

After a lot of searching, I have still not been successful in finding a solution.

CriteriaQuery<Product> query = getEntityManager().getCriteriaBuilder().createQuery(Product.class);
Root<Product> product = query.from(Product.class);
query.select(product);

return em.createQuery(query).getResultList();


Can anyone help me?

Answer

You could define the offset/limit like this:

return em.createQuery(query)
         .setFirstResult(offset) // offset
         .setMaxResults(limit) // limit
         .getResultList();

from documentation:

TypedQuery setFirstResult(int startPosition)

Set the position of the first result to retrieve. Parameters: startPosition - position of the first result, numbered from 0

TypedQuery setMaxResults(int maxResult)

Set the maximum number of results to retrieve.

Comments