Bird
Raised Fist0
Spring Bootframework~10 mins

Custom query methods by naming convention in Spring Boot - Step-by-Step Execution

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
Concept Flow - Custom query methods by naming convention
Define method name in repository
Spring Data parses method name
Generate query based on keywords
Execute query when method called
Return results to caller
Spring Data reads the method name, builds a query from it, runs the query, and returns the results.
Execution Sample
Spring Boot
interface UserRepository extends JpaRepository<User, Long> {
  List<User> findByLastName(String lastName);
}
Defines a method to find users by their last name using naming convention.
Execution Table
StepActionMethod Name ParsedQuery GeneratedResult
1Method declared: findByLastNamefindByLastNameSELECT * FROM user WHERE last_name = ?Ready to execute
2Method called with lastName='Smith'findByLastNameSELECT * FROM user WHERE last_name = 'Smith'Query executed
3Database returns matching usersN/AN/AList of users with lastName 'Smith' returned
4Method returns results to callerN/AN/ACaller receives List<User>
💡 Method execution completes after returning matching users from database
Variable Tracker
VariableStartAfter Step 2After Step 3Final
methodNamenullfindByLastNamefindByLastNamefindByLastName
querynullSELECT * FROM user WHERE last_name = 'Smith'Executed queryExecuted query
resultnullnullList<User> with lastName 'Smith'List<User> with lastName 'Smith'
Key Moments - 3 Insights
How does Spring know what query to run from the method name?
Spring parses the method name (see Step 1 in execution_table) and converts keywords like 'findByLastName' into SQL conditions automatically.
What happens if the method name does not follow naming rules?
Spring cannot parse the method name into a query, so it will throw an error at startup or runtime (not shown in this trace).
Can the method return types vary?
Yes, return types like List<User>, Optional<User>, or User are supported depending on the query and method signature.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what query is generated when calling findByLastName with 'Smith'?
ASELECT * FROM user WHERE last_name = 'Smith'
BSELECT * FROM user WHERE first_name = 'Smith'
CSELECT * FROM user WHERE name = 'Smith'
DSELECT * FROM user
💡 Hint
Check Step 2 in execution_table for the generated query.
At which step does the database return the matching users?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Result' column in execution_table rows.
If the method was named findByAge, what would change in the execution_table?
AThe method would not be parsed
BThe query would filter by age instead of last_name
CThe query would remain the same
DThe result would be empty
💡 Hint
Naming convention changes the query generated as shown in Step 1 and 2.
Concept Snapshot
Custom query methods use method names to build queries.
Method names start with findBy, readBy, getBy, etc.
Keywords after 'By' map to entity fields.
Spring Data parses method name and creates SQL automatically.
Call method with parameters to run query and get results.
Full Transcript
In Spring Boot, you can create custom queries by simply naming methods in your repository interface. For example, a method named findByLastName will be parsed by Spring Data to generate a query that selects users where the last_name matches the given parameter. When you call this method with a value like 'Smith', Spring runs the query and returns the matching users. This process involves Spring reading the method name, converting it into a SQL query, executing it, and returning the results. If the method name does not follow the naming rules, Spring will not be able to generate the query and will throw an error. This feature lets you write queries without writing SQL, just by naming methods clearly.

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'