Query Methods by Method Name
BeginnerSpring Data parses method names like findByEmailAndStatus, countByCategory, or deleteByExpiredBefore and generates the corresponding JPQL automatically.
Overview
Spring Data JPA's method name query derivation parses method names according to a grammar and generates the corresponding JPQL at startup time. Method names follow the pattern: Subject keyword (find, read, get, count, exists, delete) + By + one or more Predicate clauses joined with And/Or. Predicates can include keywords like Is, Equals, Not, Like, Containing, StartingWith, EndingWith, Between, LessThan, GreaterThan, In, IsNull, OrderBy, and many more. Method name queries are validated at startup — a typo in the property name fails fast.
Common Query Method Patterns
The most-used subject keywords and predicates cover the majority of use cases. Spring Data validates property names against the entity at startup.
public interface UserRepository extends JpaRepository<User, Long> {
// find by single field
Optional<User> findByEmail(String email);
// AND / OR
List<User> findByStatusAndRole(String status, String role);
List<User> findByEmailOrPhone(String email, String phone);
// Comparison keywords
List<User> findByAgeGreaterThan(int age);
List<User> findByCreatedAtBetween(LocalDateTime from, LocalDateTime to);
// String operations
List<User> findByNameContaining(String keyword); // LIKE %keyword%
List<User> findByEmailStartingWith(String prefix); // LIKE prefix%
// Null checks
List<User> findByPhoneIsNull();
List<User> findByPhoneIsNotNull();
// Ordered results
List<User> findByStatusOrderByCreatedAtDesc(String status);
}Count, Exists, Delete by Method Name
Beyond find, Spring Data supports count, exists (returns boolean), and delete operations derived from the method name.
public interface OrderRepository extends JpaRepository<Order, Long> {
// Count — returns long
long countByStatus(String status);
long countByCustomerIdAndStatusNot(Long customerId, String status);
// Exists — returns boolean (efficient EXISTS query, no SELECT *)
boolean existsByEmail(String email);
boolean existsByOrderNumberAndStatus(String orderNumber, String status);
// Delete by predicate — returns void or long (deleted count)
@Transactional
void deleteByStatus(String status);
@Transactional
long deleteByCreatedAtBefore(LocalDateTime cutoff);
}Projection and Top/First
Limit results with Top/First and return projections instead of full entities for efficiency. Top3, First, First10 etc. limit the query at the JPQL/SQL level.
public interface ProductRepository extends JpaRepository<Product, Long> {
// Limit with Top / First
List<Product> findTop5ByOrderByPriceDesc(); // top 5 most expensive
Optional<Product> findFirstByStatusOrderByCreatedAtAsc(String status);
// Return a projection instead of the full entity
List<ProductSummary> findByCategoryId(Long categoryId); // must define projection interface
}
// Projection interface — only selected columns loaded
public interface ProductSummary {
Long getId();
String getName();
BigDecimal getPrice();
}Key Points to Remember
- 1Method name grammar: Subject (find/count/exists/delete) + By + Predicates (And/Or/Between...)
- 2Property names are validated at startup — a typo in findByEmial causes a startup failure
- 3Comparison keywords: GreaterThan, LessThan, Between, In, IsNull, Like, Containing, etc.
- 4exists queries generate SQL EXISTS — more efficient than loading entities and checking size
- 5Top/First limits rows at the query level: findTop5By…, findFirstBy…
- 6For complex queries, switch to @Query — method names become unreadable beyond 2-3 predicates
Interview Questions
Sign in to ask AriaWhat does findByNameContaining generate as SQL?
How do existsBy methods differ from findBy in terms of generated SQL?
When should you stop using method name queries and switch to @Query?
How does Spring Data validate method name queries?
How would you write a query method that returns only the top 3 results by date?
Ask Aria about Query Methods by Method Name
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.