Queries

Basic Spring
≈ 2 min read

A query from the method name

Basic CRUD is not always enough. Applications often need to find data by a property: for example, a customer by email or only active customers. Spring Data JDBC can build queries for many simple cases from the repository method name.

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

    List<Customer> findByActiveOrderByNameAsc(boolean active);
}

In the first method, the findByEmail part specifies a condition on the email property. In the second, the condition on active is combined with sorting by name. Spring parses the method name and builds the corresponding query when the repository is used.

When the method name remains a good API

A derived query is convenient while its name reads like a normal phrase and describes one clear query. When conditions become long, complex expressions appear, or database-specific SQL is needed, trying to encode everything in a method name becomes inconvenient. An explicit query is a better fit for those cases.

The method name depends on the property names of the Java model. If an entity property is renamed, the derived query must also be checked and renamed when necessary.