VOOZH about

URL: https://www.geeksforgeeks.org/advance-java/findby-methods-in-spring-data-jpa-repositories/

⇱ findBy Methods in Spring Data JPA Repositories - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

findBy Methods in Spring Data JPA Repositories

Last Updated : 24 Oct, 2025

Spring Data JPA simplifies database interactions by eliminating boilerplate code. Its findBy methods allow developers to define queries using intuitive method names in repository interfaces. Spring Data JPA automatically interprets these method names and generates corresponding SQL queries.

Method Signatures

The findBy method follows the pattern: findBy + PropertyName [+ Condition] [+ OrderBy]. Spring interprets the method name and executes the query.

Example:

Suppose we want to fetch books by an author published after a specific year, sorted by title.

Step 1: Entity Class

Step 2: Repository Interface

Next, we will define the complex query in our repository interface.

  • Finds books by a specific author with publishedYear > year.
  • Results are sorted by title in ascending order.

Step 3: Service Layer

Using Condition Keywords in findBy Methods

Spring Data JPA supports various keywords to create complex queries directly from method names.

1. And

Combine multiple conditions

List<Book> findByAuthorAndPublishedYear(String author, int year);

2. Or

Match any one of multiple conditions

List<Book> findByAuthorOrTitle(String author, String title);

3. Combining And & Or

Suitable for complex Queries

List<Book> findByAuthorAndPublishedYearOrTitle(String author, int year, String title);

4. GreaterThan / LessThan

GreaterThan and LessThan keywords for statistical comparisons allow us to select entities whose value of the attribute is greater or less than the specified value.

List<Book> findByPublishedYearGreaterThan(int year);
List<Book> findByPublishedYearLessThan(int year);

5. Between

Used to find entities with a property value within a specified range.

List<Book> findByPublishedYearBetween(int startYear, int endYear);

6. IsNull / IsNotNull

To check for null or non-null properties:

List<Book> findByAuthorIsNull();
List<Book> findByAuthorIsNotNull();

7. Like / Containing

For partial string matching, Like and Containing keywords are particularly useful.

List<Book> findByTitleLike(String titlePattern);

List<Book> findByTitleContaining(String titleFragment);

8. StartingWith / EndingWith

To find entities with string properties starting or ending with a specific substring.

List<Book> findByTitleStartingWith(String prefix);

List<Book> findByTitleEndingWith(String suffix);

Comment

Explore