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.
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);
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.
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); }
You can use this interface like this:
Pageable topTen = new PageRequest(0, 10); List<User> result = repository.findByUsername("Matthews", topTen);
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); }
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!