Open In App

findBy Methods in Spring Data JPA Repositories

Spring Data JPA abstracts the boilerplate code required to interact with the database, allowing developers to focus more on business logic rather than database connectivity and query formation. The findBy() method, in particular, is a part of the repository layer in Spring Data JPA, enabling developers to construct queries simply by defining method signatures in interface definitions.

Method Signatures

The findBy() method uses the concept of an internal query method. The framework itself creates a query based on the method name. The naming convention begins with findBy followed by the property name. Spring Data JPA interprets the method name, translates it into an SQL query, and executes it against the database.

Suppose we are running a library management system where we need to find books by a particular author published after a certain year, and we want the results sorted by subject. This situation illustrates the need for a robust query that takes advantage of comparison operators, logical conditions, and design.

Example Application to demonstrate findBy Methods in Spring Data JPA

Step 1: Entity Class

First, let's update our Book entity to include a publishedYear field:

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String title;
    private String author;
    private int publishedYear;
    // standard constructors, getters, and setters omitted for brevity
}

Step 2: Repository Interface

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

/**
 * This interface extends JpaRepository to provide access to CRUD operations for the Book entity.
 */
public interface BookRepository extends JpaRepository<Book, Long> {

    /**
     * Finds books by author and published year greater than a given year, ordered by title in ascending order.
     *
     * @param author The author of the book.
     * @param year   The minimum published year.
     * @return A list of books matching the criteria.
     */
    List<Book> findByAuthorAndPublishedYearGreaterThanOrderByTitleAsc(String author, int year);
}

The findByAuthorAndPublishedYearGreaterThanOrderByTitleAsc method of the BookRepository interface is specified to find books by a specific author where publishedYear is greater than the specified year, results are sorted by title in ascending order.

Step 3: Service Layer

Now, let's use this method in our service layer to fetch the desired books.

/**
 * Service class to handle operations related to books.
 */
@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    /**
     * Finds books by author and published year greater than a given year, ordered by title in ascending order.
     */
    public List<Book> findBooksByAuthorPublishedAfterYear() {
        return bookRepository.findByAuthorAndPublishedYearGreaterThanOrderByTitleAsc(author, year);
    }
}

This example illustrates how Spring Data JPA enables the creation of sophisticated queries through intuitive method naming conventions, significantly reducing the effort required to interact with the database while maintaining clarity and simplicity in the codebase.

Use of Condition keywords in Spring Data JPA findBy methods

Below are some of the condition keywords with syntactical examples in Spring Data JPA findBy methods.

1. Using And in findBy methods

When we want to retrieve data that must meet multiple conditions, we use the And keyword in our method name. This will generate a query that uses the SQL AND operator to ensure all conditions are met.

Example:

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

Explanation:

This repository method finds books by a specific author and published in a specific year. The And keyword combines the conditions, so only books that match both criteria are returned.

2. Using Or in findby Methods

The Or keyword allows us to define methods that retrieve data meeting at least one of multiple conditions. It translates to the SQL OR operator in the generated query.

Example:

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

Explanation:

This method applies to books by a specific author or with a specific title. Or the keyword means that if either condition is true, the book will be included in the result.

3. Combining And, Or

We can also combine And and Or to create more complex queries.

Example:

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

Explanation:

This method searches for books by a specific author and published in a specific year or with a specific title. He combines conditions with And and Or for a more complex query requirement.

4. Using GreaterThan and LessThan in findby Methods

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.

Example:

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

Explanation:

These methods would return books published after and before the specified year, respectively.

5. Using Between in findby Methods

The Between keyword is used to find entities with a property value within a specified range.

Example:

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

Explanation:

This method returns books published between the startYear and endYear.

6. Using IsNull and IsNotNull in findby Methods

To check for null or non-null properties, IsNull and IsNotNull keywords can be used.

Example:

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

Explanation:

These methods find books where the author is either not specified or specified.

7. Using Like and Containing in findby Methods

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

Example:

List<Book> findByTitleLike(String titlePattern);
List<Book> findByTitleContaining(String titleFragment);

Explanation:

findByTitleLike would return books that match the provided title pattern (SQL LIKE), while findByTitleContaining fetches books that contain the given title fragment anywhere in their title.

8. Using StartingWith and EndingWith in findby Methods

To find entities with string properties starting or ending with a specific substring, use StartingWith or EndingWith.

Example:

List<Book> findByTitleStartingWith(String prefix);
List<Book> findByTitleEndingWith(String suffix);

Explanation:

These methods return books whose titles start or end with the specified strings.

Conclusion

All these examples showcase how we can easily construct sophisticated queries with Spring Data JPA by using condition keywords in our method names, allowing for clear and concise repository interfaces.

Article Tags :