Card 02/ 06

ExampleDifficulty: Intermediate1 min

Spring Data Example: A Query Derived From a Method Name

No SQL and no method body: the name findByStatusOrderByRequestedAtAsc is the whole query.

A derived query is a repository method whose name Spring Data reads to build the query: it splits the name into keywords and the fields of the entity (the class mapped to a table), and writes the matching query for you. The method below finds rides with a given status, oldest request first, with nothing but its name.

java
interface RideJpaRepository extends JpaRepository<RideEntity, Long> {
    List<RideEntity> findByStatusOrderByRequestedAtAsc(String status);
}

Against an H2 database (a small in-memory database used for tests) holding two waiting rides, where ride 2 was requested before ride 1:

text
derived query found 2 rides, first id=2 (earlier time)
run in a container against a real H2 database: id 2 was requested earlier than id 1

findBy starts the query, Status names the field to filter on and becomes the method's parameter, and OrderByRequestedAtAsc names the field to sort by and the direction. Spring Data parses the name at startup and builds the equivalent JPQL (JPA's query language, written against entities rather than tables).

Because the parsing happens at startup, a misspelled field name, such as findByStatsu, stops the application from starting instead of failing on the first call. So a derived query is checked before it runs, and its name documents exactly what it returns.