DEV Community

Dev Cookies
Dev Cookies

Posted on

JPA Naming Method Conventions: A Complete Guide for Developers

When working with Java Persistence API (JPA), one of the most powerful features developers leverage is the ability to define query methods simply by naming conventions — without writing actual JPQL or SQL. This is primarily supported through Spring Data JPA, which interprets method names to generate queries at runtime.

In this blog, we’ll deep-dive into:
✅ What is JPA method naming convention?
✅ The structure of JPA query method names
✅ Supported keywords and operators
✅ Examples of naming conventions
✅ Best practices
✅ Pitfalls to avoid


🌟 What Are JPA Method Naming Conventions?

In Spring Data JPA, you can define repository interface methods following a specific naming pattern. Spring automatically generates the corresponding query at runtime, removing the need to write queries manually.

👉 Example

List<User> findByFirstName(String firstName);
Enter fullscreen mode Exit fullscreen mode

➡ Spring will generate:

SELECT u FROM User u WHERE u.firstName = :firstName
Enter fullscreen mode Exit fullscreen mode

This means you focus on method names, and Spring takes care of query creation!


🛠 Structure of JPA Query Method Names

A JPA method name typically follows this structure:

<action><By><property><Operator><Condition>
Enter fullscreen mode Exit fullscreen mode

Where:

Part Example Meaning
find, read, get, query, search, count, exists, delete find, count, exists The action you want to perform
By By Indicates the beginning of the query conditions
Property FirstName, Email, Status Entity field (case-sensitive to Java field names, not DB column names)
Operator And, Or, Between Joins multiple conditions
Condition IgnoreCase, Containing, In, Like, OrderBy Adds constraints/modifiers

🔑 Common Keywords in JPA Method Names

Here’s a table of keywords you can use in method names:

Keyword Description
And, Or Combine conditions
Is, Equals, Between, LessThan, GreaterThan Comparison operators
Like, NotLike SQL LIKE pattern matching
In, NotIn Check if value is in a collection
IgnoreCase Case-insensitive match
OrderBy Sorting
Top, First Limit results
True, False Boolean checks
IsNull, IsNotNull Null checks
StartingWith, EndingWith, Containing String pattern matching

🔍 Examples of JPA Method Naming Conventions

Let’s look at practical examples:

// Find users by first name
List<User> findByFirstName(String firstName);

// Find users by last name and age
List<User> findByLastNameAndAge(String lastName, int age);

// Find users where email contains a substring
List<User> findByEmailContaining(String emailPart);

// Find users older than a certain age
List<User> findByAgeGreaterThan(int age);

// Count users by active status
long countByActiveTrue();

// Find first 3 users ordered by createdDate
List<User> findTop3ByOrderByCreatedDateDesc();
Enter fullscreen mode Exit fullscreen mode

🧠 How JPA Parses Method Names

➡ Spring Data JPA parses method names and maps parts to entity fields and query clauses.

Example:

List<User> findByFirstNameAndLastNameOrEmail(String firstName, String lastName, String email);
Enter fullscreen mode Exit fullscreen mode

Will translate to:

SELECT u FROM User u WHERE (u.firstName = :firstName AND u.lastName = :lastName) OR u.email = :email
Enter fullscreen mode Exit fullscreen mode

Note: Precedence applies: AND binds tighter than OR. Use parentheses in method names if logic is complex → but better switch to @Query in such cases.


Ordering in Method Names

To sort, you can append OrderBy followed by field(s):

List<User> findByActiveTrueOrderByCreatedDateDesc();
Enter fullscreen mode Exit fullscreen mode

➡ Equivalent to:

SELECT u FROM User u WHERE u.active = true ORDER BY u.createdDate DESC
Enter fullscreen mode Exit fullscreen mode

📌 Best Practices for JPA Method Naming

✅ Keep method names concise.
✅ Use method names for simple queries — not complex joins or subqueries.
✅ Prefer @Query for complex logic.
✅ Be mindful of property names — they should match Java field names, not DB column names.
✅ Don't overuse long method names; it reduces readability.


Common Pitfalls

Too long method names

List<User> findByFirstNameAndLastNameAndAgeAndEmailAndPhoneNumber(...);
Enter fullscreen mode Exit fullscreen mode

➡ Consider using @Query or Criteria API instead.

Wrong property name

List<User> findByfirstName(String name); // Wrong: firstName ≠ FirstName
Enter fullscreen mode Exit fullscreen mode

➡ Property names must match the exact Java field name (case-sensitive).

Combining too many conditions without clarity
Prefer splitting logic or using @Query annotation for better readability.


💡 When To Use Naming Methods vs. @Query

Use Naming Convention Use @Query / Criteria
Simple equality or basic conditions Complex joins
Limited sorting Dynamic queries
Small number of fields Subqueries
Easy to express via name Aggregations, projections

🏁 Conclusion

JPA method naming conventions are powerful for quick and clean repository definitions. They:

  • Reduce boilerplate code.
  • Are easy to read for simple queries.
  • Work well for standard CRUD operations.

However, don’t hesitate to use @Query or the Criteria API for complex scenarios to keep your code clean and maintainable.


Sample Repository Code

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByFirstName(String firstName);
    List<User> findByAgeGreaterThanAndActiveTrue(int age);
    List<User> findByEmailContainingIgnoreCase(String emailPart);
    long countByActiveTrue();
    List<User> findTop5ByOrderByCreatedDateDesc();
}
Enter fullscreen mode Exit fullscreen mode

📚 Further Reading

Top comments (0)