🎓 A1Learner
🔍
0 of 50 lessons completed

Derived Query Methods

A derived query method is a repository method whose name states the search. Spring reads the name and builds the query for you.

Name the search in the method

The method name states the search. Spring builds the query from the name.

public interface TaskRepository extends JpaRepository<Task, Long> {
    List<Task> findByDone(boolean done);
}

Ask for finished tasks

True asks for tasks marked done.

List<Task> finished = repository.findByDone(true);

Example

package com.example.demo;

import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    private final TaskRepository repository;

    public TaskController(TaskRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/tasks/done")
    public List<TaskView> tasksByDone(@RequestParam boolean done) {
        return repository.findByDone(done).stream()
                .map(task -> new TaskView(task.getTitle(), task.isDone()))
                .toList();
    }

    public record TaskView(String title, boolean done) {
    }
}

Key points

  • Spring reads the method name and builds the query.
  • findByDone takes a done flag and returns matching tasks.
  • No SQL is written by hand.
  • The name must spell a real field on the entity.
  • A derived method returns a list, even for one match.

In this example, TaskController holds the repository in a field. The constructor receives the repository when Spring builds the controller. The tasksByDone method takes the done flag from the address. It calls findByDone, and Spring builds the query from the name. Each matching task is mapped to a TaskView. The first exchange shows the one finished task. The second exchange shows the two unfinished tasks.

Note

A wrong field name in the method fails when the app starts.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does findByDone(true) return?