Customizing JPA Repositories using Derived Query Methods

Introduction

Hello! In our previous lesson, we delved into JDBC, JPA, and Spring Data JPA. We explored how to create Spring Data JPA repositories, enabling us to execute fundamental queries like findAll and findById. Today, we’ll advance our skills by learning how to write intricate custom queries using derived query methods. These methods allow you to perform more complex data retrieval operations with minimal effort.

Understanding Derived Query Methods

The concept behind derived query methods is straightforward. For simple queries, the method name in your code delineates the corresponding query. You can define methods in your JpaRepositories, and Spring Boot will automatically provide the implementation. For instance, consider the following repository method to find all items by title:

package com.codesignal.repositories;

import com.codesignal.entities.TodoItem;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface TodoItemRepository extends JpaRepository<TodoItem, Long> {
    List<TodoItem> findByTitleContaining(String title);
}

By analyzing this method name, Spring Data JPA can derive and generate the appropriate implementation for execution at runtime.

Structure of Derived Query Methods

Derived query methods follow a specific structure: <introducer>By<criteria><and | or>...<criteria><and | or>. Spring Data JPA supports introducers such as find, read, query, count, and get. It's important to note that the keywords find, read, query, and get are interchangeable and perform the same function. For example, consider the following method definitions:

List<TodoItem> findByTitle(String title);
List<TodoItem> readByTitleContaining(String title);
long countByIsCompleted(boolean isCompleted);

Each of these methods uses an introducer, followed by a conditional criterion.

Condition Types

There are various types of conditions you can use in derived queries:

  • Equality Conditions
  • Similarity Conditions
  • Comparison Conditions

These types help define the nature of the query, ranging from matching exact values to comparing ranges or partial matches.

Equality Condition Keywords

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal