Home > Java > javaTutorial > body text

How to Limit Query Results in Spring Data JPA?

Barbara Streisand
Release: 2024-10-28 08:21:02
Original
704 people have browsed it

How to Limit Query Results in Spring Data JPA?

Annotation for setMaxResults in Spring Data JPA

In Spring Data JPA versions prior to 1.7.0, it was not possible to limit the number of results returned by an annotated query method using setMaxResults. However, this feature has been introduced in Spring Data JPA 1.7.0.

New Functionality in Spring Data JPA 1.7.0

As of Spring Data JPA 1.7.0 (Evans release train), you can use the newly introduced Top and First keywords to define query methods that automatically limit the results. For example:

findTop10ByLastnameOrderByFirstnameAsc(String lastname);
Copy after login

Spring Data will automatically limit the results to the number you defined (defaulting to 1 if omitted). Note that the ordering of the results becomes relevant here, either through an OrderBy clause as seen in the example or by handing a Sort parameter into the method.

Pagination in Previous Versions

In versions of Spring Data JPA prior to 1.7.0, pagination was handled using the Pageable interface on the requesting side and the Page abstraction on the result side. Here's an example:

public interface UserRepository extends Repository<User, Long> {

  List<User> findByUsername(String username, Pageable pageable);
}
Copy after login

You can use this interface like this:

Pageable topTen = new PageRequest(0, 10);
List<User> result = repository.findByUsername("Matthews", topTen);
Copy after login

If you need more information about the result (such as which page it is or how many pages there are in total), use Page as the return type:

public interface UserRepository extends Repository<User, Long> {

  Page<User> findByUsername(String username, Pageable pageable);
}
Copy after login

This will trigger a count projection of the query to be executed to determine the total number of elements.

The above is the detailed content of How to Limit Query Results in Spring Data JPA?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!