Home  >  Article  >  Java  >  How to Limit Results in Spring-Data-JPA Query Methods?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 02:42:021014browse

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

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

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

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!

Statement:
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