Sub topic 6
Separating the API contract with DTOs
This chapter assumes you know Java records and annotations, and that you have the Book entity and BookRepository from the earlier chapters. A DTO (data transfer object) is a plain class that carries data across a boundary. Here the boundary is the HTTP API.
Why not return the entity?
Returning Book straight from a controller works in a demo. It couples three things that should change independently:
- The JSON contract. Renaming a field or column changes what clients receive.
- Writable fields. If you accept
Bookas a request body, a client can send"id": 42and try to overwrite another row. This is called mass assignment. - Persistence behavior. With
spring.jpa.open-in-view=false, serializing an entity that has lazy associations fails withLazyInitializationException, because the session is closed by the time Jackson reads them.
DTOs fix this. The request DTO lists only what a client may send. The response DTO lists only what the client may see.
Correction: the diagram must use the required fence format. Here it is in full.
Defining the request and response
Records suit DTOs because they are immutable and have no boilerplate. Each public record goes in its own file.
import jakarta.validation.constraints.NotBlank;
public record BookRequest(
@NotBlank String title,
@NotBlank String author) {
}public record BookResponse(Long id, String title, String author) {
static BookResponse from(Book book) {
return new BookResponse(book.getId(), book.getTitle(), book.getAuthor());
}
}BookRequest has no id, so a client cannot set one. BookResponse includes the id because clients need it to build URLs. The validation annotations on the request describe acceptable input. They take effect once the controller adds @Valid, which a later chapter covers.
Where the mapping happens
The service converts in both directions, as in BookService.create:
@Transactional
public BookResponse create(BookRequest request) {
Book saved = repository.save(new Book(request.title(), request.author()));
return BookResponse.from(saved);
}Converting inside the service keeps entities inside the transaction. The controller only sees DTOs, so it never touches a managed entity.
The from method is package-private. That works only if the service lives in the same package as the DTO. If you separate packages, make the method public.
Common errors
- Reusing one DTO for requests and responses. The request then needs an
idthat must be ignored, and the response carries validation annotations it does not need. Keep them separate. - Mapping in the controller. Controllers then need entity knowledge, and each endpoint repeats the conversion.
- Copying every entity field by reflex. Fields such as password hashes or audit columns should stay out of the response unless a client needs them.
- Updating by replacing the entity. In
update, load the existingBookand call its setters. Building a newBookwith the same id risks overwriting columns the request did not include.
Hand-written mapping is fine for one resource. Libraries such as MapStruct become worthwhile when many DTOs repeat the same field copying.
Exercise
A client sends POST /api/books with {"id": 99, "title": "Dune", "author": "Herbert"}. The controller accepts BookRequest. What happens to the id, and why is that useful?
Show answer
Jackson ignores the id by default in Spring Boot, because BookRequest has no such component (unknown properties are not an error unless you configure it). The service builds a new Book from title and author, so the database generates the id. The client cannot choose or overwrite a primary key.