How To Limit Number Of Records In CriteriaBuilder Query?

Viewed 359

I want to limit number of data in CriteriaBuilder so my code is like below.

typeQuery.setFirstResult(0);
typeQuery.setMaxResults(10);
typeQuery.getResultList();

but instead of limiting on Database it is fetching whole data and then fetch limit data from session.

so my question is how can i limit rows directly from database?



3 Answers

try this

Integer firstItem = 0;
Integer numOfItems = 10;

return entityManager.createQuery(typeQuery).setFirstResult(firstItem).setMaxResults(numOfItems).getResultList();

at te moment of execute te query

CriteriaBuilder converts the query to HQL/JPQL, then executes the query. HQL/JPQL doesn't support LIMIT SQL keyword or other similar keywords. Hence, either using CriteriaBuilder or HQL/JPQL, it is impossible to natively execute a limit query.

You can try limit or row_num with native though. Just another approach.

Related