Limit number of results in JPQL

JavaJpaJpql

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

You can set an offset too using setFirstResult()

em.createNamedQuery("Entity.list")
  .setFirstResult(startPosition)
  .setMaxResults(length);

Solution 3 - Java

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).

Solution 4 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionryskajakubView Question on Stackoverflow
Solution 1 - JavaNayan WadekarView Answer on Stackoverflow
Solution 2 - JavaTharakaView Answer on Stackoverflow
Solution 3 - JavaPradeep PrabhakaranView Answer on Stackoverflow
Solution 4 - JavahexhadView Answer on Stackoverflow