Spring Data JPA can automatically implement custom repository methods if their names follow a specific parsing convention, where the method name itself describes the query -- a prefix like findBy, deleteBy, or countBy followed by entity property names and optional keywords.
Key Points: • The prefix determines the operation: findBy/readBy/getBy for queries, countBy for counts, deleteBy/removeBy for deletions, existsBy for existence checks. • Property names after the prefix must exactly match (case-insensitively) the entity's field names, e.g. findByLastName maps to the lastName field. • Keywords like And, Or, Between, LessThan, GreaterThan, Like, In, and IsNull combine or refine conditions. • OrderBy followed by a property and Asc/Desc adds sorting directly into the method name. • Method parameters must appear in the same order as the properties/conditions referenced in the method name. • When the naming convention can't express the needed query, a custom @Query with JPQL or native SQL is used instead.
Example: A method named findByLastNameAndStatusOrderByCreatedAtDesc(String lastName, String status) is automatically parsed by Spring Data JPA into a query filtering by both lastName and status, sorted by createdAt descending, with zero implementation code required.
Code Example:
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
List<Employee> findByLastNameAndStatus(String lastName, String status);
long countByDepartment(String department);
boolean existsByEmail(String email);
List<Employee> findByLastNameAndStatusOrderByCreatedAtDesc(String lastName, String status);
}Interview Tip: A concise interview answer is:
"Custom repository methods follow a naming convention -- a prefix like findBy, countBy, or deleteBy, followed by entity property names, connected with keywords like And, Or, or Between, and optionally OrderBy for sorting. Spring Data JPA parses the method name at startup to generate the query, and the method's parameters just need to line up in the same order as the properties named."