Search code examples
springspring-bootspring-data-jpaspring-repositories

Spring Repository method for first()


In Grails, I can say Foo.first(). In Spring, I have repositories extending PagingAndSortingRepository and I've created a service method called getFirst() that does the following:

public Foo getFirst() {
  return fooRepository.findAll(new PageRequest(0, 1, new Sort("ASC", "id"))).getContent().get(0);
}

Is this the best way or is there a convenience method I'm just missing?


Solution

  • Create a query method on the repository interface like this:

    Foo findFirstByOrderByIdAsc();
    

    http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result