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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With