0
0
SpringbootHow-ToBeginner · 4 min read

How to Use Query By Method Name in Spring Boot

In Spring Boot, you can use query by method name by defining methods in your repository interface following naming conventions like findBy or countBy. Spring Data JPA automatically generates the query based on the method name, so you don't need to write SQL or JPQL manually.
📐

Syntax

Spring Boot uses method names in repository interfaces to create queries automatically. The method name starts with a keyword like findBy, countBy, or deleteBy, followed by the entity's field names combined with conditions.

Example parts:

  • findBy: keyword to fetch data
  • FieldName: the entity attribute to filter by
  • And/Or: combine multiple conditions
  • OrderBy: sort results
java
List<Entity> findByFieldName(String value);
Optional<Entity> findByFieldOneAndFieldTwo(String val1, String val2);
int countByStatus(String status);
void deleteByCreatedDateBefore(LocalDate date);
💻

Example

This example shows a Spring Data JPA repository interface using query by method name to find users by their last name and active status.

java
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByLastNameAndActiveTrue(String lastName);
}
Output
When calling userRepository.findByLastNameAndActiveTrue("Smith"), it returns a list of active users with last name 'Smith'.
⚠️

Common Pitfalls

Common mistakes include:

  • Using incorrect field names that don't match entity attributes causes runtime errors.
  • Not following naming conventions like missing findBy or using unsupported keywords.
  • Complex queries may require custom @Query annotations instead.
java
/* Wrong: field name typo */
List<User> findByLastNam(String lastName); // 'LastNam' should be 'LastName'

/* Correct */
List<User> findByLastName(String lastName);
📊

Quick Reference

KeywordDescriptionExample
findByFetch entities matching conditionfindByEmail(String email)
countByCount entities matching conditioncountByStatus(String status)
deleteByDelete entities matching conditiondeleteByCreatedDateBefore(LocalDate date)
AndCombine conditions with ANDfindByFirstNameAndLastName(String f, String l)
OrCombine conditions with ORfindByStatusOrRole(String s, String r)
OrderBySort resultsfindByStatusOrderByCreatedDateDesc(String status)

Key Takeaways

Define repository methods using Spring Data JPA naming conventions to auto-generate queries.
Start method names with keywords like findBy, countBy, or deleteBy followed by entity fields.
Combine multiple conditions using And, Or, and sort results with OrderBy.
Ensure method names exactly match entity attribute names to avoid errors.
Use @Query annotation for complex queries not supported by method names.