Derived Query Methods and Keyword Resolution
Build complex repository queries purely from method names using Spring Data's property-keyword grammar.
What Are Derived Query Methods?
Spring Data JPA can generate a full SQL query just by reading the name of a repository method. You write the method signature, leave the body to the framework, and Spring parses the name into a query at startup.
- No
@Queryannotation needed - No hand-written JPQL or SQL
- The method name is the query specification
This is called a derived query method, because the query is derived from the method name.
public interface UserRepository extends JpaRepository<User, Long> {
// Spring derives: SELECT u FROM User u WHERE u.email = ?1
User findByEmail(String email);
}The Subject and the Predicate
Every derived method name splits into two parts:
- The subject (an introducer like
findBy,readBy,queryBy,getBy) which tells Spring what action to perform. - The predicate (everything after
By) which becomes the WHERE clause.
In findByLastName, find is the subject and LastName is the predicate that maps to the lastName entity property.
public interface CustomerRepository extends JpaRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
List<Customer> readByCity(String city); // 'readBy' works too
Customer getById(Long id); // 'getBy' works too
}All lessons in this course
- Derived Query Methods and Keyword Resolution
- JPQL and Native Queries with @Query
- Specifications and Criteria-Based Dynamic Filtering
- Pagination, Sorting, and Slice Streaming