Limit number of results in JPQL

Viewed 53300

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

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

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

Related