Skip to main content

Derived Query Methods

By extending JpaRepository, Spring Data instantly provides generic database functions like save(), findAll(), and findById(). However, developers often need to query specifically by particular field criteria (e.g., finding a User strictly by their assigned Email address).

Instead of forcing you to write manual SQL string queries, Spring Data JPA exposes an incredibly intelligent feature called Derived Query Methods.

Method Naming Convention

If you declare a completely abstract method signature inside the generic interface exactly matching a specific naming convention standard, the framework automatically intercepts the structure and dynamically builds the raw SQL query during the application boot process.

The fundamental syntax strictly starts with the phrase findBy followed by the exact camel-cased property name mapping organically to the internal Java Entity field.

public interface UserRepository extends JpaRepository<User, Long> {

// Spring translates this to: "SELECT * FROM users WHERE email = ?"
Optional<User> findByEmail(String email);

// Translated to: "SELECT * FROM users WHERE username = ? AND age >= ?"
List<User> findByUsernameAndAgeGreaterThanEqual(String username, int age);

// Translated to: "SELECT * FROM users WHERE active = true ORDER BY created_date DESC"
List<User> findByActiveTrueOrderByCreatedDateDesc();
}

Supported Operators

Spring heavily natively supports dozens of internal keyword mappings dictating constraint boundaries:

  • And / Or
  • Between
  • LessThan / GreaterThan
  • Like / Containing
  • IgnoreCase
  • True / False

Using derived methods drastically limits errors because the Java compiler will crash natively if you misspell findByEmaiul() whereas an embedded SQL string crash (SELECT * FROM usars) will only trigger at system runtime dynamically.