Bird
Raised Fist0
Spring Bootframework~15 mins

Custom query methods by naming convention in Spring Boot - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Custom query methods by naming convention
What is it?
Custom query methods by naming convention allow you to write database queries just by naming methods in your repository interface. Instead of writing SQL or JPQL, you create method names that describe what data you want, and Spring Data JPA automatically understands and runs the right query. This makes database access simpler and faster for beginners and experts alike.
Why it matters
Without this feature, developers must write complex SQL or JPQL queries manually, which can be error-prone and slow to write. Custom query methods by naming convention save time, reduce bugs, and make code easier to read and maintain. This helps teams deliver features faster and keeps applications more reliable.
Where it fits
Before learning this, you should understand basic Spring Boot setup and how repositories work. After mastering this, you can learn advanced query techniques like @Query annotations, Criteria API, or Querydsl for more complex queries.
Mental Model
Core Idea
You tell Spring Data JPA what you want by naming methods clearly, and it builds the database query for you automatically.
Think of it like...
It's like ordering food by describing exactly what you want instead of cooking it yourself; the chef (Spring Data) understands your description and prepares the meal (query) without you needing to know the recipe (SQL).
Repository Interface
┌─────────────────────────────┐
│ findByNameAndAge(String, int)│
└─────────────┬───────────────┘
              │
              ▼
Spring Data JPA interprets method name
              │
              ▼
Generates SQL: SELECT * FROM table WHERE name = ? AND age = ?
Build-Up - 7 Steps
1
FoundationUnderstanding Repository Interfaces
🤔
Concept: Learn what a repository interface is and how it connects to the database.
In Spring Boot, a repository interface is a Java interface that extends JpaRepository or CrudRepository. It acts as a bridge between your Java code and the database. You don't write implementation code; Spring Data provides it automatically.
Result
You can call simple methods like save(), findById(), and delete() without writing SQL.
Knowing that repositories are interfaces with automatic implementations helps you trust that method names can control queries without extra code.
2
FoundationBasic Query Method Naming
🤔
Concept: Learn how method names map to simple queries.
Method names start with keywords like findBy, getBy, or readBy, followed by property names of your entity. For example, findByLastName(String lastName) will find records where lastName matches the input.
Result
Calling findByLastName("Smith") returns all records with lastName = 'Smith'.
Understanding that method names directly describe query conditions makes it easier to write queries without SQL.
3
IntermediateCombining Conditions with And/Or
🤔Before reading on: do you think findByNameOrAge returns records matching both conditions or either one? Commit to your answer.
Concept: Learn how to combine multiple conditions in method names using And and Or.
You can chain property names with And or Or to create complex queries. For example, findByNameAndAge(String name, int age) finds records where both name and age match. findByNameOrAge finds records where either name or age matches.
Result
findByNameAndAge("Alice", 30) returns records with name 'Alice' AND age 30; findByNameOrAge("Alice", 30) returns records with name 'Alice' OR age 30.
Knowing how to combine conditions lets you express more precise queries just by naming methods.
4
IntermediateUsing Keywords for Comparison Operators
🤔Before reading on: does findByAgeGreaterThan return records with age equal to or greater than the value? Commit to your answer.
Concept: Learn how keywords like GreaterThan, LessThan, Between, and Like change query comparisons.
You can add keywords to specify comparisons. For example, findByAgeGreaterThan(int age) finds records with age strictly greater than the input. findByNameLike(String pattern) finds records where name matches a pattern (using % wildcards).
Result
findByAgeGreaterThan(25) returns records with age > 25; findByNameLike("A%") returns names starting with 'A'.
Understanding these keywords lets you write queries with conditions beyond simple equality.
5
IntermediateSorting and Limiting Results
🤔
Concept: Learn how to add sorting and limits in method names.
You can add OrderBy followed by property and direction (Asc or Desc) to sort results. For example, findByLastNameOrderByAgeDesc(String lastName) returns records with lastName matching, sorted by age descending. Also, adding keywords like First or Top limits results, e.g., findTop3ByAgeLessThan(int age) returns the first 3 records with age less than input.
Result
Sorted and limited query results without extra code.
Knowing how to control order and size of results directly in method names improves query flexibility.
6
AdvancedHandling Nested Properties and Relationships
🤔Before reading on: do you think findByAddressCity works if Address is a related entity? Commit to your answer.
Concept: Learn how to query by properties of related entities using nested property names.
If your entity has a related entity (like Address inside User), you can query by nested properties using underscore or camel case. For example, findByAddressCity(String city) finds users living in a city. Spring Data understands the join and generates the correct SQL.
Result
Queries that span multiple tables using method names only.
Understanding nested property queries unlocks powerful database access without writing joins manually.
7
ExpertLimits and Surprises of Naming Conventions
🤔Before reading on: do you think every possible query can be expressed by method names alone? Commit to your answer.
Concept: Learn the boundaries of what naming conventions can express and when to use other approaches.
While naming conventions cover many queries, very complex queries with multiple joins, subqueries, or custom SQL cannot be expressed this way. Also, very long method names become hard to read and maintain. In such cases, use @Query annotations or Criteria API. Additionally, some keywords behave subtly, like findByNameContaining is case-sensitive depending on database collation.
Result
Clear understanding of when naming conventions help and when they don't.
Knowing the limits prevents frustration and guides you to better tools for complex queries.
Under the Hood
Spring Data JPA parses the method name at runtime using a parser that breaks down the method into parts: the action (find, count), the criteria (ByNameAndAge), and modifiers (OrderBy). It then maps these parts to JPQL or SQL queries using metadata from entity classes. The framework builds a query object that executes against the database, handling parameters and joins automatically.
Why designed this way?
This design was created to reduce boilerplate code and make database access more declarative and readable. Writing queries by method names fits Java's strong typing and IDE support, making it easier to catch errors early. Alternatives like writing raw SQL were error-prone and less maintainable, so this approach balances simplicity and power.
┌─────────────────────────────┐
│ Repository Interface Method  │
│ findByNameAndAge(String,int)│
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│ Method Name Parser           │
│ - Action: find              │
│ - Criteria: Name, Age       │
│ - Operator: And             │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│ Query Generator             │
│ Builds JPQL/SQL Query       │
│ SELECT e FROM Entity e WHERE│
│ e.name = ? AND e.age = ?   │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│ Database Execution          │
│ Runs query with parameters  │
│ Returns results             │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does findByNameContaining ignore case by default? Commit to yes or no.
Common Belief:People often believe that findByNameContaining always ignores case.
Tap to reveal reality
Reality:By default, findByNameContaining is case-sensitive unless the database collation or additional configuration makes it case-insensitive.
Why it matters:Assuming case-insensitivity can cause bugs where expected matches are missed, leading to confusing search results.
Quick: Can you write any SQL query using method names alone? Commit to yes or no.
Common Belief:Some think that all possible queries can be expressed by method names.
Tap to reveal reality
Reality:Complex queries with multiple joins, subqueries, or custom SQL cannot be fully expressed by method names and require @Query or Criteria API.
Why it matters:Trying to force complex queries into method names leads to unreadable code or impossible queries.
Quick: Does findByAgeGreaterThanOrEqualTo exist as a keyword? Commit to yes or no.
Common Belief:Many believe that GreaterThanOrEqualTo is a valid keyword in method names.
Tap to reveal reality
Reality:The correct keyword is GreaterThanEqual or GreaterThanEquals; using incorrect keywords causes runtime errors.
Why it matters:Using wrong keywords leads to application startup failures or confusing errors.
Quick: Does findByNameAndAge return results if only one condition matches? Commit to yes or no.
Common Belief:Some think findByNameAndAge returns results if either name or age matches.
Tap to reveal reality
Reality:findByNameAndAge requires both conditions to be true; it uses AND logic, not OR.
Why it matters:Misunderstanding AND vs OR leads to wrong query results and bugs.
Expert Zone
1
Method name parsing is case-sensitive and strict; small typos cause runtime errors, so IDE support and tests are crucial.
2
Using nested properties in method names triggers joins automatically, but excessive nesting can degrade performance and readability.
3
Some keywords like IsNull, Not, and Exists add subtle behavior changes that can optimize queries but are often overlooked.
When NOT to use
Avoid using naming conventions for very complex queries involving multiple joins, aggregations, or database-specific functions. Instead, use @Query annotations with JPQL or native SQL, or Criteria API for dynamic queries.
Production Patterns
In real projects, developers use naming conventions for simple CRUD and common queries, combine with @Query for complex cases, and write integration tests to verify query correctness. They also limit method name length to keep code readable and maintainable.
Connections
Domain-Driven Design (DDD)
Builds-on
Understanding entity properties and relationships in DDD helps design meaningful method names that reflect business queries.
Natural Language Processing (NLP)
Similar pattern
Both parse structured text (method names or sentences) into meaningful actions, showing how naming conventions rely on language parsing concepts.
SQL Query Optimization
Builds-on
Knowing how generated queries translate to SQL helps optimize method names to produce efficient database queries.
Common Pitfalls
#1Using incorrect keyword in method name causing runtime error
Wrong approach:List findByAgeGreaterThanOrEqualTo(int age);
Correct approach:List findByAgeGreaterThanEqual(int age);
Root cause:Misunderstanding the exact keywords supported by Spring Data JPA method name parser.
#2Expecting case-insensitive search without configuration
Wrong approach:List findByNameContaining(String namePart); // expects case-insensitive
Correct approach:List findByNameIgnoreCaseContaining(String namePart);
Root cause:Not realizing that case sensitivity depends on database collation or explicit IgnoreCase keyword.
#3Writing overly long method names that are hard to read
Wrong approach:List findTop5ByStatusAndAddressCityAndAgeGreaterThanOrderByLastNameDesc(String status, String city, int age);
Correct approach:Use @Query annotation for complex queries instead of very long method names.
Root cause:Trying to express too much logic in method names reduces readability and maintainability.
Key Takeaways
Custom query methods by naming convention let you write database queries by simply naming methods clearly in repository interfaces.
Spring Data JPA parses method names into queries, saving you from writing SQL and reducing errors.
You can combine conditions, use comparison keywords, sort, limit, and query nested properties all via method names.
There are limits to what method names can express; complex queries need other tools like @Query or Criteria API.
Understanding the exact keywords and syntax is crucial to avoid runtime errors and unexpected behavior.

Practice

(1/5)
1. What does a Spring Data JPA method named findByLastName do?
easy
A. Counts records where the lastName matches the given value
B. Deletes records where the lastName matches the given value
C. Checks if any record exists with the given lastName
D. Finds all records where the lastName matches the given value

Solution

  1. Step 1: Understand the method prefix

    The prefix findBy in Spring Data JPA means it will search and return matching records.
  2. Step 2: Analyze the property name

    The method uses LastName as the property to filter by, so it finds records with that lastName.
  3. Final Answer:

    Finds all records where the lastName matches the given value -> Option D
  4. Quick Check:

    findBy + property = find matching records [OK]
Hint: findBy means search and return matching records [OK]
Common Mistakes:
  • Confusing findBy with deleteBy or countBy
  • Thinking it returns a boolean instead of records
  • Ignoring the property name after findBy
2. Which of the following is the correct syntax for a method that counts users by their age in Spring Data JPA?
easy
A. findCountByAge(int age);
B. countUsersByAge(int age);
C. countByAge(int age);
D. countAgeBy(int age);

Solution

  1. Step 1: Identify the correct prefix for counting

    The correct prefix to count records is countBy.
  2. Step 2: Check method naming pattern

    The method should be countByAge to count users filtered by age.
  3. Final Answer:

    countByAge(int age); -> Option C
  4. Quick Check:

    countBy + property = count matching records [OK]
Hint: Use countBy + property to count records [OK]
Common Mistakes:
  • Adding extra words like Users in method name
  • Using findCountBy which is invalid
  • Placing property name after count instead of after By
3. Given the method existsByEmailAndStatus(String email, String status), what will it return if a user with email "test@example.com" and status "active" exists?
medium
A. A list of users matching the email and status
B. true
C. false
D. The count of users matching the email and status

Solution

  1. Step 1: Understand the method prefix

    The prefix existsBy returns a boolean indicating if any record matches the criteria.
  2. Step 2: Analyze the condition

    The method checks if a user exists with the given email and status combined with And.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    existsBy + conditions returns boolean [OK]
Hint: existsBy returns true if matching record exists [OK]
Common Mistakes:
  • Expecting a list instead of boolean
  • Confusing existsBy with findBy
  • Ignoring the combined conditions with And
4. Identify the error in this Spring Data JPA method declaration: List<User> findByNameOr(int age, String name);
medium
A. The method name is missing the property after 'Or'
B. The method should use 'And' instead of 'Or' for combining conditions
C. The order of parameters does not match the method name conditions
D. The return type should be boolean for 'findBy' methods

Solution

  1. Step 1: Analyze the method name structure

    The method name uses 'Or' but does not specify the property after 'Or'. It should be like 'findByNameOrAge'.
  2. Step 2: Check parameter order and names

    Parameters should match the properties in the method name order, but the main error is missing property after 'Or'.
  3. Final Answer:

    The method name is missing the property after 'Or' -> Option A
  4. Quick Check:

    Method names must specify property after 'Or' [OK]
Hint: After 'Or' or 'And', always specify property name [OK]
Common Mistakes:
  • Leaving out property name after 'Or' or 'And'
  • Mixing parameter order with method name order
  • Using wrong return type for findBy methods
5. You want to create a method that finds all orders where the customer's city is "New York" and the order total is greater than 100. Which method name correctly follows Spring Data JPA naming conventions?
hard
A. findByCustomerCityAndOrderTotalGreaterThan(String city, double total);
B. findOrdersByCityAndTotalGreater(String city, double total);
C. findByCityAndOrderTotalGreaterThan(String city, double total);
D. findByCustomerCityAndOrderTotalGreater(String city, double total);

Solution

  1. Step 1: Identify the correct property names

    The properties are nested: customer.city and orderTotal. The method name must reflect this exactly.
  2. Step 2: Use correct keywords for comparison

    For 'greater than', the keyword is 'GreaterThan' in Spring Data JPA method names.
  3. Step 3: Combine conditions with 'And'

    The method name should combine both conditions with 'And' and use full property paths.
  4. Final Answer:

    findByCustomerCityAndOrderTotalGreaterThan(String city, double total); -> Option A
  5. Quick Check:

    Use full property names + GreaterThan + And [OK]
Hint: Use full property names and 'GreaterThan' for > comparisons [OK]
Common Mistakes:
  • Using incomplete property names
  • Using 'Greater' instead of 'GreaterThan'
  • Omitting 'By' after 'find'