Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit number of results in JPQL

Tags:

java

jpa

jpql

How it is possible to limit the number of results retrieved from a database?

select e from Entity e /* I need only 10 results for instance */
like image 540
ryskajakub Avatar asked Aug 13 '10 17:08

ryskajakub


People also ask

How do you limit records in JPA?

JPA Setup In our repository method, we use the EntityManager to create a Query on which we call the setMaxResults() method. This call to Query#setMaxResults will eventually result in the limit statement appended to the generated SQL: select passenger0_.id as id1_15_, passenger0_.

Does JPQL support the limit keyword for pagination?

JPQL doesn't support the LIMIT keyword.

How do I set the fetch size in JPA?

hibernate. fetchSize", "100"); Or when using Spring Data JPA use a @QueryHints annotation on the interface method. Can be applied to both methods with and without @Query .


2 Answers

You can try like this giving 10 results to be fetched explicitly.

entityManager.createQuery(JPQL_QUERY)              .setParameter(arg0, arg1)              .setMaxResults(10)              .getResultList(); 

It will automatically create native query in back-end to retrieve specific number of results, if the backend supports it, and otherwise do the limit in memory after getting all results.

like image 151
Nayan Wadekar Avatar answered Oct 10 '22 14:10

Nayan Wadekar


You can set an offset too using setFirstResult()

em.createNamedQuery("Entity.list")   .setFirstResult(startPosition)   .setMaxResults(length); 
like image 33
Tharaka Avatar answered Oct 10 '22 15:10

Tharaka