Derived Query Methods by Convention

Harry · 11 Sep 2026 · 11 views

Derived Query Methods by Convention

Spring Data can translate well-chosen method names into queries, letting you describe intent instead of writing SQL. The parser reads the subject and predicates, then generates and caches the matching query. Getting to know the grammar means writing correct queries on the first try.

Naming grammar

Start with a subject such as find, read, count, or existsBy, then chain property paths with keywords: findByEmail, countByStatusActiveTrue, deleteByExpiredAtBefore. Each segment refers to a real entity property.

interface PostRepository extends JpaRepository<Post, Long> {
    List<Post> findByAuthorId(Long authorId);
    List<Post> findByTitleContainingIgnoreCase(String part);
    long countByCommentsEmpty();
    List<Post> findTop5ByOrderByPublishedAtDesc();
}

Operators and combinations

Keywords cover Containing, GreaterThan, Between, In, IsNull, and boolean properties. Chain predicates with And and Or, and use IgnoreCase where case-insensitive matching is needed. Sort with OrderBy or a Sort parameter.

Limits in the name

Prefixes like First, Top, and Distinct shape results: findFirstByOrderByCreatedAtDesc returns the newest row. The method name is the contract, so keep it readable before optimizing.

When conventions are not enough

Long nested names are brittle and hard to read. When a name becomes a sentence, switch to @Query with explicit JPQL. The parser fails fast with a clear error at startup, so mistakes surface early.

Key Points

  • Method names derive queries from property paths and keywords.
  • Combine subjects, predicates, and operators with And, Or, and IgnoreCase.
  • Use Top, First, and Distinct to shape result limits.
  • Use @Query when a method name would grow unreadable.
  • A validation error appears at startup when a name is invalid.
Share this post:

Comments (0)

Please login or register to comment.