Foundation · Build

Derived Query Methods

Method names like findBySkuIgnoreCase compile into queries at startup; the parser rejects typos and unknown properties before the app ever serves a request.

Primary source: Spring Data JPA: Query Creation from Method Names

20 min

Lesson 6 of 17

1d streak

The Architectural Question

Names past three And clauses stop communicating; at that size an explicit @Query documents intent better than grammar gymnastics.

What this guide proves

  • Method Naming
  • findBy
  • Pagination

How the PartTree query parser interprets method names

Spring Data decomposes method names using keywords into JPQL queries automatically. Knowing the grammar prevents subtle querying bugs.

Method NameKeywordGenerated SQL Where Clause
findByStatus(Status s)EqualsWHERE status = ?
findByCustomerEmailIgnoreCase(String email)IgnoreCaseWHERE UPPER(customer_email) = UPPER(?)
findByCreatedAtBetween(Instant s, Instant e)BetweenWHERE created_at BETWEEN ? AND ?
findTop10ByOrderByTotalDesc()Top / OrderByORDER BY total DESC LIMIT 10

Break it deliberately: Invalid property name in method signature

Terminal / Diagnostic Output
org.springframework.data.mapping.PropertyReferenceException:
No property 'statuss' found for type 'OrderEntity'! Did you mean 'status'?

Startup validation

Spring Data validates all derived query method signatures against the entity properties during ApplicationContext startup. Typos cannot slip into production.

Active Recall Checkpoint

When should you transition from a derived query method to an explicit @Query annotation?

Hint: Consider method name length and readability.

Show answer & explanation

When the method name exceeds 3-4 criteria (e.g. findByStatusAndCustomerEmailAndCreatedAtAfterOrderByTotalDesc), or when joins and projections are required. Long derived query names are unreadable and error-prone.

Derived query selection guidelines

Use it when

Use derived queries for simple 1-2 criteria lookups on indexed columns.

Reconsider when

Avoid derived queries with complex outer joins, subqueries, or dynamic predicates; use JPQL or Specifications.

Working Implementation

Code Walkthrough

Write a derived query to find all active products created after a certain date, sorted by price descending.

ProductRepository.java
public interface ProductRepository extends JpaRepository<Product, UUID> {
    Optional<Product> findBySkuIgnoreCase(String sku);

    boolean existsBySkuIgnoreCase(String sku);

    Page<Product> findByActiveTrueAndNameContainingIgnoreCase(
            String name,
            Pageable pageable
    );
}

// The caller controls page number, size, and a safe mapped sort.
var page = PageRequest.of(0, 20, Sort.by("name").ascending());
Page<Product> result = products
        .findByActiveTrueAndNameContainingIgnoreCase("keyboard", page);
Spring Data parses each method name against the entity metamodel at startup, so a typo like findBySkuu breaks the context instead of a request.
Derived names stay readable for two or three predicates; past that, @Query or a Specification says more than the name can.
Page runs a second count query for the total; Slice only asks whether one more row exists.

Synthesis & Production Verification

Deliberate Failure Condition

  1. Break: Type findByFirtName with a typo
  2. Observe: PropertyReferenceException at bootstrap
  3. Repair: Spring Data validates every derived query against entity metadata during startup, which is exactly when you want it to fail.

Production Acceptance Criteria

  • Write a findBy method with two conditions plus ordering
  • Add Pageable and return Slice or Page results
  • Explain what startup validation catches before any test runs

Architectural & Technical Review

Core Interview Questions

Q01How does the Spring Data PartTree parser process method names?Show answer

It decomposes prefixes like findBy with keywords like Between, And, IgnoreCase into parameterized JPQL queries.

Q02How does Spring Data prevent invalid property names in derived query methods?Show answer

It validates every method name against entity properties during ApplicationContext startup, throwing PropertyReferenceException if a field is missing.

Q03When should derived queries be replaced with explicit @Query annotations?Show answer

When method names become excessively long or when custom joins, groupings, or projections are required.

Production Pitfalls

Critical Anti-Patterns

  • Pitfall: Writing unindexed multi-property queries — Derived queries across unindexed columns trigger sequential table scans that degrade as table rows grow.
  • Pitfall: Ignoring case sensitivity in string lookups — Querying without IgnoreCase can lead to missed matches in case-insensitive search expectations.

Primary Documentation & Specifications