🎓 A1Learner
🔍
0 of 50 lessons completed

Reading Tasks

Reading tasks means fetching saved rows from the database. A repository reads them with findAll and findById.

Read every task

findAll asks the repository for all saved tasks.

List<Task> tasks = repository.findAll();

Read one task

findById asks for the task with one id. The answer may be empty.

Optional<Task> task = repository.findById(2L);

Example

package com.example.demo;

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

@RestController
public class TaskController {

    private final TaskRepository repository;

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

    @GetMapping("/tasks")
    public List<TaskView> allTasks() {
        return repository.findAll().stream()
                .map(task -> new TaskView(task.getTitle(), task.isDone()))
                .toList();
    }

    @GetMapping("/tasks/{id}")
    public TaskView oneTask(@PathVariable Long id) {
        Task task = repository.findById(id).orElseThrow();
        return new TaskView(task.getTitle(), task.isDone());
    }

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

Key points

  • A repository is the object that talks to the database.
  • findAll returns every saved task.
  • findById takes an id and returns one task.
  • findById returns an Optional.
  • An Optional is a box that holds a task or holds nothing.
  • Map each task to a title and a done flag before sending it.

In this example, TaskController holds the repository in a field. The constructor receives the repository when Spring builds the controller. The allTasks method reads every task with findAll. Each task is mapped to a TaskView with only a title and a done flag. The oneTask method reads one task with findById. The first exchange shows all three tasks in seed order. The second exchange shows the task with id 2.

Note

The JSON answer shows only title and done, never the generated id.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which method reads every saved task?