Skip to content
Tutorials Center
My learning

Topics

Lesson 111 of 119 ยท Projects

Project: Task API with Spring Boot

Rebuild a JSON task API with Spring Boot 4 - entities, Spring Data JPA, Bean Validation, ProblemDetail errors, paging, PATCH, optimistic locking and slice tests.

In Project: A REST API from Scratch you built a task API with nothing but the JDK, Jackson and H2: a router, request helpers, a JDBC repository, a service with hand-written validation, and exception mapping to problem details. It worked, and you understood every line. It also took about 400 lines of plumbing before the first business rule.

In this project you rebuild the same API with the same contract in Spring Boot, using Spring MVC, Spring Data JPA, Jakarta Bean Validation and Spring's ProblemDetail. The goal is not only to get a working Spring application, but to see exactly which piece of your from-scratch code each annotation replaces, where Spring behaves slightly differently, and which new capabilities (like optimistic locking) come almost for free.

Spring can't run in this page's editor, so the application is a guided multi-file walkthrough: every file is shown in full with its path, in the order you would write it. Three runnable examples show what Spring does underneath: the SQL that Spring Data and Hibernate run for you, the domain logic under plain JUnit tests, and optimistic locking done by hand. The framework background is in Spring Boot Introduction, Building REST APIs with Spring Boot and Validation and Error Handling.

The contract stays the same

Clients must not notice the rewrite. The API keeps every promise from the previous project:

Request Success Errors
GET /tasks?status=&sort=&page=&size= 200 + page object 400 bad parameter
GET /tasks/{id} 200 + task 400, 404
POST /tasks 201 + task + Location 400, 415
PUT /tasks/{id} 200 + task 400, 404, 409
PATCH /tasks/{id} 200 + task 400, 404, 409
DELETE /tasks/{id} 204 404

The rules are also the same: the title is required, trimmed and at most 100 characters; status defaults to TODO and priority to MEDIUM; a new task's due date can't be in the past; a DONE task is final. Errors are RFC 9457 problem details with an errors array for invalid fields. The Spring version adds one rule: if two clients edit the same task at the same time, the second one gets 409 Conflict instead of silently overwriting the first.

Project layout

Create the project with Spring Initializr (Spring Boot 4, Java 25, Maven) and the dependencies Spring Web, Spring Data JPA, Validation and H2 Database. The finished project looks like this:

TEXT
task-api/
โ”œโ”€โ”€ pom.xml
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ main/
    โ”‚   โ”œโ”€โ”€ java/com/example/tasks/
    โ”‚   โ”‚   โ”œโ”€โ”€ TaskApiApplication.java
    โ”‚   โ”‚   โ”œโ”€โ”€ task/
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Status.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Priority.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ PriorityConverter.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Task.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ TaskRepository.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ TaskRequest.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ TaskResponse.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ PageResponse.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ TaskNotFoundException.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ TaskDoneException.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ InvalidTaskException.java
    โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ TaskService.java
    โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ TaskController.java
    โ”‚   โ”‚   โ””โ”€โ”€ web/
    โ”‚   โ”‚       โ””โ”€โ”€ ApiExceptionHandler.java
    โ”‚   โ””โ”€โ”€ resources/
    โ”‚       โ””โ”€โ”€ application.properties
    โ””โ”€โ”€ test/java/com/example/tasks/task/
        โ”œโ”€โ”€ TaskControllerTest.java
        โ””โ”€โ”€ TaskRepositoryTest.java

The code is packaged by feature: everything about tasks lives in task, and only cross-cutting web concerns sit in web. Many classes in task can then be package-private, so other features can't reach into them. Layered Architecture compares this with packaging by layer.

The build and the configuration

The pom.xml inherits from Boot's parent, which manages every version, and lists the starters. Spring Boot 4 renamed the web starter to spring-boot-starter-webmvc and ships matching test starters per technology; in Boot 3 you would use spring-boot-starter-web and a single spring-boot-starter-test. See Maven in Depth for how parents and starters work.

XML
<!-- pom.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.1.1</version>            <!-- use the latest 4.x release -->
    <relativePath/>
  </parent>

  <groupId>com.example</groupId>
  <artifactId>task-api</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <properties>
    <java.version>25</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webmvc-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

The configuration file replaces the hand-written setup in startServer and main:

PROPERTIES
# src/main/resources/application.properties
spring.application.name=task-api

# In-memory H2 for development; production overrides these with environment variables
spring.datasource.url=jdbc:h2:mem:tasks
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true

# Don't keep the persistence context open while JSON is written
spring.jpa.open-in-view=false

# Reject unknown JSON fields, like the from-scratch version
spring.jackson.deserialization.fail-on-unknown-properties=true

# One virtual thread per request, like Executors.newVirtualThreadPerTaskExecutor()
spring.threads.virtual.enabled=true

Three of these lines are decisions, not defaults:

  • ddl-auto=create-drop lets Hibernate create the table from the entity at startup. That is convenient while learning and wrong for production, where a migration tool such as Flyway owns the schema (the first runnable example below is effectively that migration).
  • open-in-view=false turns off a Boot default that keeps a database session open until the response is written. With it on, a lazy relationship touched in the controller or by Jackson silently triggers extra queries. Turning it off forces the service to return finished DTOs, which is cleaner anyway.
  • fail-on-unknown-properties=true restores the strict behavior of the previous project. Boot's own default ignores unknown fields.

The application class

Java
// src/main/java/com/example/tasks/TaskApiApplication.java
package com.example.tasks;

import java.time.Clock;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class TaskApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(TaskApiApplication.class, args);
    }

    @Bean
    Clock clock() {
        return Clock.systemDefaultZone();
    }
}

@SpringBootApplication turns on component scanning for com.example.tasks and below, and auto-configuration. The Clock bean is the same idea as before: the service asks for a Clock in its constructor, production gets the system clock, and tests can supply a fixed one. This is the dependency injection you did by hand in startServer, now done by the container (Dependency Injection and Inversion of Control).

The domain: enums, entity and converter

The enums are unchanged, except that Priority now carries a rank:

Java
// src/main/java/com/example/tasks/task/Status.java
package com.example.tasks.task;

public enum Status { TODO, IN_PROGRESS, DONE }
Java
// src/main/java/com/example/tasks/task/Priority.java
package com.example.tasks.task;

public enum Priority {
    LOW(1), MEDIUM(2), HIGH(3);

    private final int rank;

    Priority(int rank) {
        this.rank = rank;
    }

    public int rank() {
        return rank;
    }

    public static Priority fromRank(int rank) {
        for (Priority priority : values()) {
            if (priority.rank == rank) {
                return priority;
            }
        }
        throw new IllegalArgumentException("Unknown priority rank " + rank);
    }
}

Remember the CASE expression the JDBC repository needed so that priorities sort as LOW, MEDIUM, HIGH instead of alphabetically? With JPA you sort by entity properties, not SQL expressions, so the clean fix is to store a number. A JPA AttributeConverter translates between the enum and the column. Storing @Enumerated(EnumType.ORDINAL) would also give numbers, but ordinals change when someone inserts a new constant in the middle; an explicit rank never does.

Java
// src/main/java/com/example/tasks/task/PriorityConverter.java
package com.example.tasks.task;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

@Converter
class PriorityConverter implements AttributeConverter<Priority, Integer> {

    @Override
    public Integer convertToDatabaseColumn(Priority priority) {
        return priority == null ? null : priority.rank();
    }

    @Override
    public Priority convertToEntityAttribute(Integer rank) {
        return rank == null ? null : Priority.fromRank(rank);
    }
}

The entity replaces the Task record, the SCHEMA text block and the row mapper. It can't be a record, because JPA needs a no-argument constructor and mutable fields to load and track it (Entities and Hibernate Setup). Note where the "done is final" rule went: into the entity's own update method. The entity protects its invariants itself, so no service, batch job or future endpoint can bypass the rule.

Java
// src/main/java/com/example/tasks/task/Task.java
package com.example.tasks.task;

import jakarta.persistence.*;
import java.time.LocalDate;

@Entity
@Table(indexes = @Index(name = "task_by_status", columnList = "status"))
public class Task {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 100)
    private String title;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 20)
    private Status status;

    @Convert(converter = PriorityConverter.class)
    @Column(nullable = false)
    private Priority priority;

    private LocalDate dueDate;

    @Version
    private long version;

    protected Task() {
        // for JPA
    }

    public Task(String title, Status status, Priority priority, LocalDate dueDate) {
        this.title = title;
        this.status = status;
        this.priority = priority;
        this.dueDate = dueDate;
    }

    /** Replaces every editable field. A finished task can't be changed. */
    public void update(String title, Status status, Priority priority, LocalDate dueDate) {
        if (this.status == Status.DONE) {
            throw new TaskDoneException(id);
        }
        this.title = title;
        this.status = status;
        this.priority = priority;
        this.dueDate = dueDate;
    }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public Status getStatus() { return status; }
    public Priority getPriority() { return priority; }
    public LocalDate getDueDate() { return dueDate; }
    public long getVersion() { return version; }
}

The @Version field is new. Hibernate increments it on every update and adds AND version = ? to the UPDATE statement. If another transaction changed the row in the meantime, no row matches, and Spring throws ObjectOptimisticLockingFailureException. That closes the "read, check, write" gap the previous project accepted. The third runnable example shows the SQL behind it.

The repository

The whole JdbcTaskRepository, about 90 lines, becomes this:

Java
// src/main/java/com/example/tasks/task/TaskRepository.java
package com.example.tasks.task;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

interface TaskRepository extends JpaRepository<Task, Long> {

    Page<Task> findByStatus(Status status, Pageable pageable);
}

JpaRepository already provides save, findById, findAll(Pageable), existsById, deleteById and more. findByStatus is a derived query: Spring Data parses the method name, builds the query where status = ?, and because the return type is Page and a Pageable is passed, it also runs a count query and applies the sort and the offset. Run the example to see the SQL this produces.

Java The schema and SQL that Spring Data JPA runs for you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The two HIGH tasks with status TODO come first, in id order, and the count query reports four matching tasks in two pages. This pair of queries is exactly what you wrote by hand in JdbcTaskRepository.find. Spring Data adds one optimization: when the first page already holds fewer rows than the page size, it knows the total without running the count query.

To see the real SQL in your own project, keep spring.jpa.show-sql=true while developing, or set logging.level.org.hibernate.SQL=debug to send it through the logger. Reading the generated SQL is the best habit you can build with JPA; it is how you spot the N+1 problem early (Fetching Strategies and the N+1 Problem).

DTOs: what clients send and receive

TaskRequest replaces TaskInput, and the validation that TaskService.validate did by hand for the title moves into annotations. @Valid on a controller parameter makes Spring check them before your method runs.

Java
// src/main/java/com/example/tasks/task/TaskRequest.java
package com.example.tasks.task;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.time.LocalDate;

public record TaskRequest(
        @NotBlank @Size(max = 100) String title,
        Status status,
        Priority priority,
        LocalDate dueDate) {

    Status statusOrDefault() {
        return status == null ? Status.TODO : status;
    }

    Priority priorityOrDefault() {
        return priority == null ? Priority.MEDIUM : priority;
    }
}

The response types are separate records, so the entity never reaches Jackson. That keeps internal fields like version out of the JSON, and lets the entity change without breaking clients.

Java
// src/main/java/com/example/tasks/task/TaskResponse.java
package com.example.tasks.task;

import java.time.LocalDate;

public record TaskResponse(long id, String title, Status status, Priority priority, LocalDate dueDate) {

    static TaskResponse from(Task task) {
        return new TaskResponse(task.getId(), task.getTitle(), task.getStatus(), task.getPriority(), task.getDueDate());
    }
}
Java
// src/main/java/com/example/tasks/task/PageResponse.java
package com.example.tasks.task;

import java.util.List;
import org.springframework.data.domain.Page;

public record PageResponse<T>(List<T> items, int page, int size, long totalItems, int totalPages) {

    static <T> PageResponse<T> from(Page<T> page) {
        return new PageResponse<>(page.getContent(), page.getNumber() + 1, page.getSize(),
            page.getTotalElements(), page.getTotalPages());
    }
}

PageResponse keeps the page format of the previous project, with 1-based page numbers. Spring Data's Page counts from 0, and serializing a Page object directly gives a large, implementation-specific JSON structure (recent Spring Data versions log a warning when you do it). Mapping to your own record makes the format a deliberate part of the contract.

Exceptions and the service

The domain exceptions are the same as before, plus InvalidTaskException for the one rule annotations can't express, because it needs the Clock:

Java
// src/main/java/com/example/tasks/task/TaskNotFoundException.java
package com.example.tasks.task;

public class TaskNotFoundException extends RuntimeException {
    public TaskNotFoundException(long id) {
        super("Task " + id + " not found");
    }
}
Java
// src/main/java/com/example/tasks/task/TaskDoneException.java
package com.example.tasks.task;

public class TaskDoneException extends RuntimeException {
    public TaskDoneException(Long id) {
        super("Task " + id + " is done and can no longer be changed");
    }
}
Java
// src/main/java/com/example/tasks/task/InvalidTaskException.java
package com.example.tasks.task;

public class InvalidTaskException extends RuntimeException {
    private final String field;

    public InvalidTaskException(String field, String message) {
        super(message);
        this.field = field;
    }

    public String field() {
        return field;
    }
}

The service is almost the same as the from-scratch one. @Transactional on the class runs every public method in a transaction, and read-only methods say so. Look at replace: it never calls save. The task loaded by findById is managed by the persistence context, so Hibernate notices the changed fields and writes them at commit. This is dirty checking (Entity Lifecycle and Transactions).

Java
// src/main/java/com/example/tasks/task/TaskService.java
package com.example.tasks.task;

import java.time.Clock;
import java.time.LocalDate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TaskService {

    private final TaskRepository repository;
    private final Clock clock;

    TaskService(TaskRepository repository, Clock clock) {
        this.repository = repository;
        this.clock = clock;
    }

    public TaskResponse create(TaskRequest request) {
        if (request.dueDate() != null && request.dueDate().isBefore(LocalDate.now(clock))) {
            throw new InvalidTaskException("dueDate", "must not be in the past");
        }
        Task task = new Task(request.title().strip(), request.statusOrDefault(),
            request.priorityOrDefault(), request.dueDate());
        return TaskResponse.from(repository.save(task));
    }

    @Transactional(readOnly = true)
    public TaskResponse get(long id) {
        return TaskResponse.from(find(id));
    }

    @Transactional(readOnly = true)
    public PageResponse<TaskResponse> list(Status status, Pageable pageable) {
        Page<Task> page = status == null
            ? repository.findAll(pageable)
            : repository.findByStatus(status, pageable);
        return PageResponse.from(page.map(TaskResponse::from));
    }

    public TaskResponse replace(long id, TaskRequest request) {
        Task task = find(id);
        task.update(request.title().strip(), request.statusOrDefault(),
            request.priorityOrDefault(), request.dueDate());
        return TaskResponse.from(task);                // no save(): dirty checking writes it at commit
    }

    public void delete(long id) {
        if (!repository.existsById(id)) {
            throw new TaskNotFoundException(id);
        }
        repository.deleteById(id);
    }

    private Task find(long id) {
        return repository.findById(id).orElseThrow(() -> new TaskNotFoundException(id));
    }
}

delete checks existsById first because deleteById in current Spring Data versions silently does nothing for a missing id, and the contract promises a 404.

The service and the entity contain all the business rules, and none of them need Spring to run. That is worth proving: the next example is a plain-Java copy of Task and TaskService without the annotations, with the repository replaced by a small in-memory fake, tested with JUnit. In the real project you would write the same tests, with the fake or with Mockito; no Spring context is needed.

Java Unit tests for the domain logic, no Spring needed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

All seven tests pass in milliseconds. replaceChangesTheManagedTask works here because the fake hands out the same object it stores, which is a fair model of what the persistence context does inside one transaction. Whether Hibernate really writes the change at commit is a different question, answered by the @DataJpaTest later in this walkthrough.

The controller

The controller replaces Router, Request and TaskController from the previous project. Each handler method is one line or close to it, because Spring does the parsing:

Java
// src/main/java/com/example/tasks/task/TaskController.java
package com.example.tasks.task;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Valid;
import jakarta.validation.Validator;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import java.net.URI;
import java.util.Set;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.node.ObjectNode;

@RestController
@RequestMapping("/tasks")
class TaskController {

    private static final Set<String> SORTABLE = Set.of("id", "title", "priority", "dueDate");

    private final TaskService service;
    private final JsonMapper jsonMapper;
    private final Validator validator;

    TaskController(TaskService service, JsonMapper jsonMapper, Validator validator) {
        this.service = service;
        this.jsonMapper = jsonMapper;
        this.validator = validator;
    }

    @GetMapping
    PageResponse<TaskResponse> list(
            @RequestParam(required = false) Status status,
            @RequestParam(defaultValue = "id") String sort,
            @RequestParam(defaultValue = "1") @Min(1) @Max(1000) int page,
            @RequestParam(defaultValue = "10") @Min(1) @Max(50) int size) {
        return service.list(status, PageRequest.of(page - 1, size, toSort(sort)));
    }

    @GetMapping("/{id}")
    TaskResponse get(@PathVariable long id) {
        return service.get(id);
    }

    @PostMapping
    ResponseEntity<TaskResponse> create(@Valid @RequestBody TaskRequest request) {
        TaskResponse task = service.create(request);
        return ResponseEntity.created(URI.create("/tasks/" + task.id())).body(task);
    }

    @PutMapping("/{id}")
    TaskResponse replace(@PathVariable long id, @Valid @RequestBody TaskRequest request) {
        return service.replace(id, request);
    }

    @PatchMapping("/{id}")
    TaskResponse patch(@PathVariable long id, @RequestBody ObjectNode changes) {
        ObjectNode merged = jsonMapper.valueToTree(service.get(id));
        merged.remove("id");
        merged.setAll(changes);                                // absent fields stay, null clears
        TaskRequest request = jsonMapper.treeToValue(merged, TaskRequest.class);
        Set<ConstraintViolation<TaskRequest>> violations = validator.validate(request);
        if (!violations.isEmpty()) {
            throw new ConstraintViolationException(violations);
        }
        return service.replace(id, request);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    void delete(@PathVariable long id) {
        service.delete(id);
    }

    private static Sort toSort(String sort) {
        boolean descending = sort.startsWith("-");
        String property = descending ? sort.substring(1) : sort;
        if (!SORTABLE.contains(property)) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                "sort must be id, title, priority or dueDate, optionally prefixed with -");
        }
        Sort primary = Sort.by(descending ? Sort.Direction.DESC : Sort.Direction.ASC, property);
        return primary.and(Sort.by("id"));                     // tie-breaker for stable paging
    }
}

Walk through what disappeared:

  • Routing is @GetMapping("/{id}") and friends. Spring answers 404 for unknown paths and 405 with an Allow header for wrong methods by itself.
  • @PathVariable long id converts the path segment; /tasks/abc becomes a 400 without your code running.
  • @RequestParam with defaults replaces parseQuery, and @Min/@Max replace intParam. Since Spring Framework 6.1, constraint annotations on parameters are checked automatically and fail with HandlerMethodValidationException (400).
  • @RequestBody replaces the body helper, including the 415 for a wrong content type and the 400 for broken JSON.
  • @Valid runs Bean Validation on the request record.
  • The sort whitelist stays. Spring Data validates property names against the entity, so the SQL injection risk from the previous project is gone, but you still decide which properties are public sort keys. Without the whitelist, sort=version would expose an internal field.

PATCH keeps its JSON-merge logic, now with Spring's auto-configured JsonMapper. Boot 4 uses Jackson 3, whose packages start with tools.jackson; with Boot 3 you would import com.fasterxml.jackson.databind instead and the code would be the same (JSON with Jackson explains the move). Because the merged request doesn't arrive as an @Valid parameter, the method validates it with the injected Jakarta Validator, so PUT and PATCH enforce the same rules.

Two small behavior differences from the from-scratch version are worth knowing. First, @Valid runs before the service, so a request with a blank title and a past due date reports only the title; the due-date rule is checked after the title is fixed. Second, Spring converts ?status=done with Enum.valueOf, which is case-sensitive, so clients must send DONE. Both are fixable (a custom constraint with a ClockProvider, a case-insensitive Converter), and both are the kind of detail a contract test catches.

Errors as problem details

ApiExceptionHandler replaces Router.toProblem. Extending ResponseEntityExceptionHandler makes all of Spring MVC's built-in errors (404, 405, 415, unreadable JSON, type mismatches, parameter validation) render as ProblemDetail with the application/problem+json content type. The methods below add the project's own exceptions and reshape validation errors into the same errors array as before.

Java
// src/main/java/com/example/tasks/web/ApiExceptionHandler.java
package com.example.tasks.web;

import com.example.tasks.task.InvalidTaskException;
import com.example.tasks.task.TaskDoneException;
import com.example.tasks.task.TaskNotFoundException;
import jakarta.validation.ConstraintViolationException;
import java.util.Comparator;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import tools.jackson.core.JacksonException;

@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler {

    record InvalidField(String field, String message) {}

    @ExceptionHandler(TaskNotFoundException.class)
    ProblemDetail notFound(TaskNotFoundException e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
    }

    @ExceptionHandler(TaskDoneException.class)
    ProblemDetail done(TaskDoneException e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
    }

    @ExceptionHandler(ObjectOptimisticLockingFailureException.class)
    ProblemDetail concurrentChange(ObjectOptimisticLockingFailureException e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
            "The task was changed by someone else; reload it and try again");
    }

    @ExceptionHandler(InvalidTaskException.class)
    ProblemDetail invalidTask(InvalidTaskException e) {
        return invalid(List.of(new InvalidField(e.field(), e.getMessage())));
    }

    @ExceptionHandler(ConstraintViolationException.class)
    ProblemDetail constraintViolation(ConstraintViolationException e) {
        return invalid(e.getConstraintViolations().stream()
            .map(v -> new InvalidField(v.getPropertyPath().toString(), v.getMessage()))
            .toList());
    }

    @ExceptionHandler(JacksonException.class)
    ProblemDetail unreadable(JacksonException e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "The request body doesn't match the task format");
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException e,
            HttpHeaders headers, HttpStatusCode status, WebRequest request) {
        List<InvalidField> errors = e.getBindingResult().getFieldErrors().stream()
            .map(error -> new InvalidField(error.getField(), error.getDefaultMessage()))
            .toList();
        return handleExceptionInternal(e, invalid(errors), headers, status, request);
    }

    private static ProblemDetail invalid(List<InvalidField> errors) {
        List<InvalidField> sorted = errors.stream().sorted(Comparator.comparing(InvalidField::field)).toList();
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST,
            "The task has " + sorted.size() + " invalid field" + (sorted.size() == 1 ? "" : "s"));
        problem.setProperty("errors", sorted);
        return problem;
    }
}

setProperty("errors", ...) adds an extension member, which RFC 9457 explicitly allows. The errors are sorted because Bean Validation reports violations in no guaranteed order, and a stable order makes the API and its tests predictable.

The ObjectOptimisticLockingFailureException handler is where @Version pays off. What Hibernate does is easy to show with plain JDBC: every update carries the version the client read, and a stale version updates zero rows.

Java Optimistic locking with a version column, by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Ana's update wins and bumps the version to 1. Ben's update still says version = 0, matches no row, and is refused, so Ana's change is not lost. After reloading, Ben's update succeeds. No locks are held while users think, which is why this approach scales well for web applications where most edits don't collide. In an API, the version is often exposed as an ETag header and checked with If-Match (REST API Design); within a single request, as here, @Version already protects the window between findById and commit.

Tests

The from-scratch project had service tests with a fake and API tests over real HTTP. Spring Boot offers test slices that start only part of the application, which keeps tests fast while still exercising Spring's machinery.

@WebMvcTest starts only the web layer: controllers, the advice, Jackson and validation, with MockMvc to send requests without a real server. The service is replaced by a Mockito mock through @MockitoBean, so these tests check routing, status codes, validation and the error format, and nothing else (Test Doubles and Mockito).

Java
// src/test/java/com/example/tasks/task/TaskControllerTest.java
package com.example.tasks.task;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;

@WebMvcTest(TaskController.class)
class TaskControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockitoBean
    TaskService service;

    @Test
    void createReturns201WithLocation() throws Exception {
        when(service.create(any())).thenReturn(new TaskResponse(1, "Water plants", Status.TODO, Priority.MEDIUM, null));

        mockMvc.perform(post("/tasks").contentType(MediaType.APPLICATION_JSON).content("""
                {"title": "Water plants"}"""))
            .andExpect(status().isCreated())
            .andExpect(header().string("Location", "/tasks/1"))
            .andExpect(jsonPath("$.status").value("TODO"));
    }

    @Test
    void blankTitleIsRejectedBeforeTheServiceRuns() throws Exception {
        mockMvc.perform(post("/tasks").contentType(MediaType.APPLICATION_JSON).content("""
                {"title": " "}"""))
            .andExpect(status().isBadRequest())
            .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
            .andExpect(jsonPath("$.errors[0].field").value("title"));
        verifyNoInteractions(service);
    }

    @Test
    void unknownFieldsAreRejected() throws Exception {
        mockMvc.perform(post("/tasks").contentType(MediaType.APPLICATION_JSON).content("""
                {"id": 5, "title": "Sneaky"}"""))
            .andExpect(status().isBadRequest());
    }

    @Test
    void doneTasksAnswer409() throws Exception {
        when(service.replace(eq(1L), any())).thenThrow(new TaskDoneException(1L));

        mockMvc.perform(put("/tasks/1").contentType(MediaType.APPLICATION_JSON).content("""
                {"title": "Pay rent", "status": "TODO"}"""))
            .andExpect(status().isConflict())
            .andExpect(jsonPath("$.detail").value("Task 1 is done and can no longer be changed"));
    }

    @Test
    void unknownSortKeysAndHugePagesAreBadRequests() throws Exception {
        mockMvc.perform(get("/tasks").param("sort", "version")).andExpect(status().isBadRequest());
        mockMvc.perform(get("/tasks").param("size", "500")).andExpect(status().isBadRequest());
    }
}

@DataJpaTest starts only JPA: entities, repositories and an embedded H2 database. Each test runs in a transaction that is rolled back at the end, so tests don't see each other's data. This is where the converter, the derived query and the generated SQL get tested against a real database.

Java
// src/test/java/com/example/tasks/task/TaskRepositoryTest.java
package com.example.tasks.task;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

@DataJpaTest
class TaskRepositoryTest {

    @Autowired
    TaskRepository repository;

    @Test
    void sortsByPriorityRankWithAStableTieBreaker() {
        for (Priority priority : List.of(Priority.LOW, Priority.HIGH, Priority.MEDIUM, Priority.HIGH, Priority.LOW)) {
            repository.save(new Task("Task " + priority, Status.TODO, priority, null));
        }

        Page<Task> page = repository.findByStatus(Status.TODO,
            PageRequest.of(0, 2, Sort.by(Sort.Direction.DESC, "priority").and(Sort.by("id"))));

        assertThat(page.getTotalElements()).isEqualTo(5);
        assertThat(page.getTotalPages()).isEqualTo(3);
        assertThat(page.getContent()).extracting(Task::getPriority).containsExactly(Priority.HIGH, Priority.HIGH);
    }

    @Test
    void updatesIncrementTheVersion() {
        Task task = repository.saveAndFlush(new Task("Draft", Status.TODO, Priority.LOW, null));
        long before = task.getVersion();

        task.update("Final", Status.IN_PROGRESS, Priority.LOW, null);
        repository.flush();                                    // dirty checking writes the UPDATE now

        assertThat(task.getVersion()).isEqualTo(before + 1);
    }
}

Boot 4 moved the test-slice annotations into per-technology modules, which is why the imports read org.springframework.boot.webmvc.test.autoconfigure and org.springframework.boot.data.jpa.test.autoconfigure. In Boot 3 the same annotations live in org.springframework.boot.test.autoconfigure.web.servlet and ...orm.jpa; your IDE suggests the right import. A full end-to-end test with @SpringBootTest (the whole application, optionally on a random port) completes the pyramid; Testing Spring Boot Applications covers it along with Testcontainers.

Running it

From the project folder, start the application with the Maven wrapper and try the API with curl (read-only commands; they need a real machine):

Terminal
./mvnw spring-boot:run

curl -i -X POST localhost:8080/tasks -H "Content-Type: application/json" \
     -d '{"title": "Write quarterly report", "priority": "HIGH", "dueDate": "2030-03-20"}'
curl "localhost:8080/tasks?sort=-priority&size=2"
curl -X PATCH localhost:8080/tasks/1 -H "Content-Type: application/json" -d '{"status": "DONE"}'
curl -i -X PUT localhost:8080/tasks/1 -H "Content-Type: application/json" -d '{"title": "Reopen"}'

./mvnw test

The first call answers 201 Created with Location: /tasks/1, and with spring.jpa.show-sql=true the console shows the insert Hibernate ran. The list call returns the same page object as the from-scratch API. After the PATCH marks the task done, the PUT answers 409 with a problem detail. ./mvnw test runs both test classes. (The exact order of fields in the JSON can differ from the previous project, because Jackson 3's defaults differ from Jackson 2's; clients should never depend on field order.)

What each piece replaced

From-scratch project Spring Boot project
HttpServer + virtual-thread executor Embedded Tomcat + spring.threads.virtual.enabled=true
startServer wiring with constructors Component scanning + constructor injection
Router.route("GET", "/tasks/{id}", ...), 404/405 @GetMapping("/{id}"); built-in 404/405
req.id(), parseQuery, intParam @PathVariable, @RequestParam, @Min/@Max
req.body(...) with 415 and Jackson error mapping @RequestBody + ResponseEntityExceptionHandler
convert rejecting unknown fields spring.jackson.deserialization.fail-on-unknown-properties=true
Title checks in TaskService.validate @NotBlank @Size(max = 100) + @Valid
Due-date check with Clock Same check in the service, InvalidTaskException
Router.toProblem + Problem record @RestControllerAdvice + ProblemDetail
SCHEMA text block + RowMapper @Entity mapping (Flyway migration in production)
JdbcTaskRepository (90 lines) TaskRepository extends JpaRepository (1 method)
CASE expression for priority order AttributeConverter storing the rank
OFFSET/FETCH + COUNT(*) Pageable + Page
"Last write wins" @Version optimistic locking, 409
Service tests with a fake The same, or Mockito; no Spring needed
API tests over real HTTP @WebMvcTest + MockMvc, @DataJpaTest, @SpringBootTest

The code shrank from roughly 500 lines to about 300, and almost all of the remaining code is the domain and the contract, the parts that are specific to your application. Just as important, nothing about the design changed: the same layers, the same DTOs, the same domain exceptions, the same rules. Spring removed the plumbing, not the thinking.

Ideas for extending the project

  • Flyway migrations. Add spring-boot-starter-flyway, move the schema into src/main/resources/db/migration/V1__create_task.sql, and set spring.jpa.hibernate.ddl-auto=validate so Hibernate only checks that the entity matches.
  • PostgreSQL in Docker. Run PostgreSQL with Docker Compose for development and Testcontainers in tests (Docker for Java Developers).
  • ETags. Return the version as an ETag and require If-Match for PUT and PATCH, answering 412 on a mismatch.
  • Search and filters. Add findByTitleContainingIgnoreCase or a Specification for combined filters (Spring Data JPA).
  • Security. Protect write endpoints with Spring Security and JWTs, and record who created each task (Spring Security, JWT and OAuth 2).
  • Observability. Add Actuator for /actuator/health and request metrics (Actuator, Metrics and Observability).
  • API documentation. Generate an OpenAPI description from the controller with springdoc-openapi.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. TaskService.replace changes the entity's fields but never calls repository.save. Why is the change still stored?

    Entities loaded inside a transaction are tracked by the persistence context. At flush or commit, Hibernate compares them with their loaded state and issues UPDATE statements for changed ones.
  2. 2. Two clients load task 5 at version 3. Client A saves first. What happens when client B saves?

    With @Version, Hibernate adds "and version = ?" to the UPDATE. A stale version updates zero rows, which is reported as an optimistic locking failure.
  3. 3. Why does the Spring version store priority with an AttributeConverter instead of @Enumerated(EnumType.STRING)?

    JPA sorts by the column value. Strings sort as HIGH, LOW, MEDIUM; an explicit numeric rank sorts by meaning and, unlike ORDINAL, doesn't change when constants are added.
  4. 4. A client sends POST /tasks with a blank title and a due date in the past. What does the Spring version report?

    Bean Validation runs on the @Valid parameter before the controller method, so the service's due-date rule is never reached. It's a real behavior difference worth documenting or fixing with a custom constraint.
  5. 5. Which test annotation starts only controllers, advice, Jackson and validation, with MockMvc and no database?

    @WebMvcTest is the web slice. Collaborators such as the service are supplied as mocks with @MockitoBean.

Summary

  • The rewrite keeps the contract and the design (layers, DTOs, domain exceptions, rules) and replaces the plumbing with Spring Boot.
  • application.properties replaces setup code; decide ddl-auto, open-in-view and Jackson's unknown-field behavior deliberately.
  • The entity owns its invariants (update refuses a done task), uses an AttributeConverter for a meaningful priority order, and gets optimistic locking from @Version.
  • A one-method Spring Data repository replaces the JDBC repository; Pageable runs the paged query and the count for you.
  • The controller is thin: mappings, @PathVariable, @RequestParam with constraints, @Valid @RequestBody, a sort whitelist, and a JSON-merge PATCH validated with the injected Validator.
  • One @RestControllerAdvice extending ResponseEntityExceptionHandler turns every error into a ProblemDetail.
  • Test the domain with plain JUnit, the web layer with @WebMvcTest, persistence with @DataJpaTest, and the whole app with @SpringBootTest.

Next: Project: Banking Application with JDBC.