As of Spring Data JPA 1.7.0 (Evans release).
You can use the recently introduced Top and First keywords that allow you to define query methods as follows:
findTop10ByLastnameOrderByFirstnameAsc(String lastname);
Spring Data will automatically limit the results to the number you specify (the default is 1 if not specified). Note that here the ordering of the results becomes relevant (either using the OrderBy clause, as shown in the example, or by passing the Sort parameter to the method). Read more about this in the Spring Data Evans new release features blog or documentation .
For previous versions
To extract only pieces of data, Spring Data uses the page numbering abstraction that comes with the Pageable interface on the requestor, as well as the Page abstraction on the results side. So you could start with
public interface UserRepository extends Repository<User, Long> { List<User> findByUsername(String username, Pageable pageable); }
and use it like this:
Pageable topTen = new PageRequest(0, 10); List<User> result = repository.findByUsername("Matthews", topTen);
If you need to know the context of the result (which page is it really? Is it the first? How many?), Use Page as the return type:
public interface UserRepository extends Repository<User, Long> { Page<User> findByUsername(String username, Pageable pageable); }
Then the client code can do something like this:
Pageable topTen = new PageRequest(0, 10); Page<User> result = repository.findByUsername("Matthews", topTen); Assert.assertThat(result.isFirstPage(), is(true));
Itโs not that we started the projection of counting the actual query that will be executed if you use Page as the return type, since we need to find out how many elements are in total to calculate metadata. Also, make sure that you really have equipped PageRequest with PageRequest information to get consistent results. Otherwise, you can run the query twice and get other results, even if the data has not changed.