Home > Java > javaTutorial > body text

How to Limit Results in Spring-Data-JPA Query Methods?

Mary-Kate Olsen
Release: 2024-10-28 02:42:02
Original
946 people have browsed it

How to Limit Results in Spring-Data-JPA Query Methods?

How to Use setMaxResults Annotation in Spring-Data-JPA

Your question pertains to setting the maximum number of results returned by a query method in Spring-Data-JPA using annotations.

Solution

Since Spring Data JPA 1.7.0 (Evans release train) introduced the Top and First keywords, you can define query methods like this:

findTop10ByLastnameOrderByFirstnameAsc(String lastname);
Copy after login

Spring Data will automatically limit the results to the specified number (defaulting to 1 if omitted). Remember that the ordering of the results becomes important in this case.

Previous Versions

In earlier versions, Spring Data used the pagination abstraction for retrieving data slices. Here's how to use it:

public interface UserRepository extends Repository<User, Long> {

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

//...

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

If you require the context of the result, you can use Page as the return type:

public interface UserRepository extends Repository<User, Long> {

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

//...

Pageable topTen = new PageRequest(0, 10);
Page<User> result = repository.findByUsername("Matthews", topTen);
Assert.assertThat(result.isFirstPage(), is(true));
Copy after login

Note that using Page as the return type will trigger a count projection to determine the total number of elements.

The above is the detailed content of How to Limit Results in Spring-Data-JPA Query Methods?. 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!