57

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 */
ryskajakub
  • 6,096
  • 8
  • 44
  • 71

4 Answers4

70

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.

Paŭlo Ebermann
  • 71,139
  • 18
  • 140
  • 206
Nayan Wadekar
  • 11,136
  • 4
  • 44
  • 70
  • 5
    "It will automatically create native query in back-end to retrieve specific number of results" - only if the database and the dialect supports it. If not, JPA will query all results and filter them in-memory. The developer must be aware of that, since it may affect the performance a lot. What's more, with some (more complicated) queries, JPA doesn't even try to use the LIMIT/TOP functionality, for instance when it would lead to wrong results. – Adam Dyga Nov 28 '13 at 12:33
  • 1
    @AdamDyga Yes, it's implementation specific, some provide them explicitly. Thanks for adding information. – Nayan Wadekar Nov 29 '13 at 07:53
20

You can set an offset too using setFirstResult()

em.createNamedQuery("Entity.list")
  .setFirstResult(startPosition)
  .setMaxResults(length);
UkFLSUI
  • 5,161
  • 6
  • 32
  • 45
Tharaka
  • 2,415
  • 1
  • 20
  • 13
2

If you are using Spring data JPA, then you can use Pageable/PageRequest to limit the record to 1 or any number you want. The first argument, is the page no, and the second argument is the number of records.

Pageable page = PageRequest.of(0, 1);
Entity e = entityRepository.findAll(page);

Make sure the entityRepostitory interface extends JpaRepository (which supports sorting and pagination).

0

Import

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

Repository

@Query(value = "select * from table");
public Page<Dto> limited(Pageable pageable);

Service

Page<Dto> returnValue= repo.limited(PageRequest.of(0, 1));
return returnValue.getContent();

just try with and without getContent();
PageRequest.of(0, X) X = Limit

hexhad
  • 851
  • 10
  • 12