Limit number of results in JPQL

coubeatczech picture coubeatczech · Aug 13, 2010 · Viewed 50.9k times · Source

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 */

Answer

Nayan Wadekar picture Nayan Wadekar · Aug 16, 2010

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.