Finding by a Field
Finding by a field searches tasks by one named value. A derived method like findByTitle searches the title field.
Search the title field
The method name must spell the field exactly.
List<Task> found = repository.findByTitle("Buy milk");Take the title from the address
The value after title= in the address lands in this value.
@GetMapping("/tasks/search")
public List<TaskView> byTitle(@RequestParam String title) {
return repository.findByTitle(title).stream()
.map(task -> new TaskView(task.getTitle(), task.isDone()))
.toList();
}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/search")
public List<TaskView> tasksByTitle(@RequestParam String title) {
return repository.findByTitle(title).stream()
.map(task -> new TaskView(task.getTitle(), task.isDone()))
.toList();
}
public record TaskView(String title, boolean done) {
}
}Key points
- findByTitle takes a title and returns matching tasks.
- The method name must spell the field exactly.
- The search value arrives as a request parameter.
- A request parameter follows a question mark in the address.
- A search with no match returns an empty list.
- An empty list means no task has that title.
In this example, TaskController holds the repository in a field. The constructor receives the repository when Spring builds the controller. The tasksByTitle method takes the title from the address. It calls findByTitle, and Spring builds the query from the name. Each matching task is mapped to a TaskView. The first exchange shows the one task with that title. The second exchange shows an empty list, since no task has that title.
Note
Titles match exactly, so letter case matters.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method finds tasks by title?