Home/Learn/Hibernate & JPA/Query Methods by Method Name

Query Methods by Method Name

Beginner
Spring Data JPA

Spring 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.

Java — query method name examples
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.

Java — count, exists, delete derived methods
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.

Java — Top/First limiting and projection return types
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 Aria
1

What does findByNameContaining generate as SQL?

EasyTCS
2

How do existsBy methods differ from findBy in terms of generated SQL?

MediumInfosys
3

When should you stop using method name queries and switch to @Query?

MediumAmazon
4

How does Spring Data validate method name queries?

EasyWipro
5

How would you write a query method that returns only the top 3 results by date?

EasyAccenture

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.

Loading discussion…