Derived Queries

Basic Spring
≈ 2 min read

A query directly in the method name

Many simple selections do not need separate JPQL. Spring Data JPA can parse a repository method name and build a query from its structure. The part after By describes entity properties and search conditions.

interface CustomerRepository extends JpaRepository<Customer, Long> {
    Optional<Customer> findByEmail(String email);

    List<Customer> findByActiveTrueOrderByNameAsc();

    List<Customer> findByAgeGreaterThan(int age);
}

The findByEmail method searches by the email property. The second name expresses both the active = true condition and sorting by name, while GreaterThan expresses a “greater than” comparison. Spring Data builds the query from entity metadata — no SQL is written by hand here.

Names should remain readable

A derived query is convenient while the condition can be understood from a short method name. For example, combinations of supported keywords such as And, Or, Between, and In can express many common filters. But a long name with five conditions is already harder to read than an explicit query or a separate dynamic filter.

Spring Data validates properties in method names when the repository is created. A typo such as findByEamil is usually detected when the application starts, not only when the method is called for the first time.