Custom query methods let you find data easily without writing SQL. You just name the method to tell Spring Boot what to search for.
Custom query methods by naming convention in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Spring Boot
List<Entity> findByPropertyName(Type value); Optional<Entity> findByPropertyName(Type value); boolean existsByPropertyName(Type value); long countByPropertyName(Type value); List<Entity> findByPropertyNameAndOtherProperty(Type value1, Type value2);
Method names start with findBy, existsBy, or countBy.
Use And, Or to combine conditions in method names.
Examples
Spring Boot
List<User> findByLastName(String lastName);
Spring Boot
Optional<User> findByEmail(String email);
Spring Boot
boolean existsByUsername(String username);
Spring Boot
List<Product> findByPriceLessThan(Double price);
Sample Program
This example shows a Spring Data JPA repository with custom query methods named by convention. The service class calls these methods and prints results.
Spring Boot
package com.example.demo.repository; import com.example.demo.model.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface UserRepository extends JpaRepository<User, Long> { List<User> findByLastName(String lastName); Optional<User> findByEmail(String email); boolean existsByUsername(String username); } // Sample usage in a service class package com.example.demo.service; import com.example.demo.model.User; import com.example.demo.repository.UserRepository; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public void demoQueries() { List<User> smiths = userRepository.findByLastName("Smith"); System.out.println("Users with last name Smith: " + smiths.size()); Optional<User> userOpt = userRepository.findByEmail("alice@example.com"); System.out.println("User with email alice@example.com found: " + userOpt.isPresent()); boolean exists = userRepository.existsByUsername("alice123"); System.out.println("User with username alice123 exists: " + exists); } }
Important Notes
Spring Boot creates the query automatically based on method name.
Make sure property names in method match entity field names exactly.
Use Optional return type when you expect zero or one result.
Summary
Custom query methods let you search data by naming methods clearly.
Use prefixes like findBy, existsBy, countBy.
Combine conditions with And or Or in method names.
Practice
1. What does a Spring Data JPA method named
findByLastName do?easy
Solution
Step 1: Understand the method prefix
The prefixfindByin Spring Data JPA means it will search and return matching records.Step 2: Analyze the property name
The method usesLastNameas the property to filter by, so it finds records with that lastName.Final Answer:
Finds all records where the lastName matches the given value -> Option DQuick 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
Solution
Step 1: Identify the correct prefix for counting
The correct prefix to count records iscountBy.Step 2: Check method naming pattern
The method should becountByAgeto count users filtered by age.Final Answer:
countByAge(int age); -> Option CQuick 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
Solution
Step 1: Understand the method prefix
The prefixexistsByreturns a boolean indicating if any record matches the criteria.Step 2: Analyze the condition
The method checks if a user exists with the given email and status combined withAnd.Final Answer:
true -> Option BQuick 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
Solution
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'.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'.Final Answer:
The method name is missing the property after 'Or' -> Option AQuick 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
Solution
Step 1: Identify the correct property names
The properties are nested: customer.city and orderTotal. The method name must reflect this exactly.Step 2: Use correct keywords for comparison
For 'greater than', the keyword is 'GreaterThan' in Spring Data JPA method names.Step 3: Combine conditions with 'And'
The method name should combine both conditions with 'And' and use full property paths.Final Answer:
findByCustomerCityAndOrderTotalGreaterThan(String city, double total); -> Option AQuick 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'
