Sub topic 6
Separating the API Contract with DTOs
This chapter assumes you know Java records, JPA entity basics, and how a Spring @RestController returns JSON. It covers why the API should expose its own request and response types instead of the Book entity, how to write them, and where the mapping code belongs.
What a DTO is and why the entity should stay private
A DTO (data transfer object) is a plain class or record that carries data across a boundary. Here the boundary is the HTTP API. The Book entity is a persistence model. It describes how data sits in a table and is managed by Hibernate. The DTOs describe what clients send and receive.
You could return the entity directly from the controller, and Jackson would serialize it. It works at first. It causes problems as the application grows:
- Coupling. Renaming a field or column changes the JSON, which breaks clients.
- Over-posting. If the entity is the request body, a client can send fields you never meant to expose, such as
id, or a futureroleorpricefield. - Lazy loading. Serializing an entity can touch lazy associations. With
spring.jpa.open-in-view=false(set in the database configuration chapter), this throwsLazyInitializationExceptionoutside a transaction. - Cycles. Bidirectional relationships (author to books to author) make Jackson recurse until it fails.
- One shape for everything. Create needs no
id. Responses need it. Entities cannot express that difference.
DTOs fix these by making the contract explicit, and a change to the table no longer has to change the JSON.
The entity never crosses the arrow between the service and the controller. Only DTOs do.
Request and response records
Java records suit DTOs. They are immutable, have no boilerplate, and Jackson (2.12 and later, which Spring Boot 3 includes) reads and writes them without extra configuration.
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());
}
}The imports you need are jakarta.validation.constraints.NotBlank for the request. The response record needs none.
Compare the two records:
| Aspect | `BookRequest` | `BookResponse` |
|---|---|---|
| Direction | Client to server | Server to client |
| Has `id` | No, the server generates it | Yes |
| Validation annotations | Yes | No |
| Used for | POST and PUT bodies | All responses |
The request has no id. For POST, the database generates it. For PUT, the id comes from the URL path. Keeping it out of the body removes any ambiguity about which one wins when they disagree.
The validation annotations on BookRequest describe acceptable input. A later chapter shows how @Valid in the controller enforces them. For now, notice that the rules live on the contract type and not on the entity. Your persistence model can then hold data that was created by other means, such as imports, without being tied to API rules.
Unknown and missing fields
Spring Boot configures Jackson with FAIL_ON_UNKNOWN_PROPERTIES disabled. A client who sends {"title":"A","author":"B","id":99} gets no error. Jackson ignores id because the record has no such component. That is the protection against over-posting: only the fields declared on the DTO can ever reach your code.
A missing field is different. For a record, an absent JSON property becomes null. With @NotBlank, null is rejected during validation. Without a constraint, null flows into the service. Every field a client must supply needs a constraint.
Mapping between entity and DTO
Something has to convert in both directions. The simplest approach is a static factory on the response record, as shown above, plus a constructor call on the entity side:
Book book = new Book(request.title(), request.author());
BookResponse response = BookResponse.from(book);For a resource with three fields, this is enough. It is also explicit: the compiler checks every field, and a new entity field requires a deliberate decision about whether to expose it.
Where mapping should live
Keep mapping in the service layer or in the DTO itself, and not in the controller. The service is where the transaction runs, so it is the safe place to read entity fields, including lazy ones. The controller then deals only with DTOs.
The service from this tutorial follows that rule:
@Transactional(readOnly = true)
public BookResponse get(Long id) {
return repository.findById(id)
.map(BookResponse::from)
.orElseThrow(() -> new BookNotFoundException(id));
}The entity is loaded and converted inside the transaction. The controller receives a BookResponse, which has no connection to Hibernate.
Updates and dirty checking
The update method maps a request onto an existing entity:
@Transactional
public BookResponse update(Long id, BookRequest request) {
Book book = repository.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));
book.setTitle(request.title());
book.setAuthor(request.author());
return BookResponse.from(book);
}There is no call to save. The entity is managed inside the transaction, so Hibernate compares it with its loaded snapshot at commit and issues an UPDATE for any changes. This is dirty checking. The DTO never touches the managed entity directly. The service copies selected values, which is how you control which fields can change.
Because PUT replaces the resource, BookRequest must contain every updatable field. If you later want PATCH, which changes only some fields, you need a different request type where fields may be absent. Do not reuse BookRequest for that, because its @NotBlank rules would reject partial bodies.
Mapping libraries
Libraries such as MapStruct generate mapping code at compile time. They pay off when you have many resources with many fields, because they remove repetitive code and still fail the build when a field is unmapped (if configured to do so). Reflection-based mappers such as ModelMapper move errors to runtime. For this one-resource API, hand-written mapping is clearer, and it is the choice this tutorial makes.
Records and the entity: why the entity is not a record
It is tempting to turn Book into a record too. JPA does not support that. An entity needs a no-argument constructor, non-final fields, and often a proxy subclass that Hibernate generates, and records are final with final fields. Use records for DTOs and ordinary classes for entities. The entity in this tutorial uses a protected no-argument constructor for JPA and a public constructor for your own code.
Versioning and evolving the contract
DTOs give you room to evolve the API:
- Adding a response field is usually backward compatible. Clients that ignore unknown fields keep working.
- Removing or renaming a field breaks clients. Introduce a new DTO type, and a new URL version if needed, such as
/api/v2/books. - Adding a required request field breaks existing clients, because their requests will fail validation. Make it optional first, or version the endpoint.
Because the entity is separate, you can add a database column such as isbn without changing any JSON until you decide to.
Common mistakes
- Returning the entity "just for now". It tends to stay. Start with DTOs, since the cost is two small records.
- Mapping outside the transaction. If
BookResponse.fromtouches a lazy association after the transaction ends, you getLazyInitializationException. Map inside the service method. - Putting
@Validconstraints on the entity instead of the request. The entity is then validated on persist, which producesConstraintViolationExceptionand a 500 response, instead of a 400 at the boundary. - One DTO for everything. A single
BookDtowith an optionalidmakes validation rules ambiguous. Separate request and response types are clearer. - Copying every field by reflection. Generic copy utilities such as
BeanUtils.copyPropertiescan silently copy fields you did not intend to expose or update.
Checking the contract
You can confirm the DTO behavior with a quick request after starting the application (the database must be configured as in the earlier chapter):
curl -s -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"id": 99, "title": "Refactoring", "author": "Martin Fowler"}'The response contains an id generated by the database, not 99, because the request record has no id component:
{"id":1,"title":"Refactoring","author":"Martin Fowler"}Exercise
A teammate changes the Book entity by adding a String internalNotes field for staff use. The controller returns BookResponse, built with BookResponse.from(book). Does internalNotes appear in the JSON, and why? What would change if the controller returned Book directly?
Show answer
It does not appear. BookResponse is a record with only id, title, and author, and from copies only those. A new entity field reaches clients only if someone adds it to the record and to from. If the controller returned Book directly, Jackson would serialize every property that has a getter, so internalNotes would be exposed if a getter exists. Anyone adding a getter later would also expose it without noticing.
Exercise
A client sends PUT /api/books/5 with the body {"id": 7, "title": "New", "author": "Ada"}. Which book is updated, and what happens to the 7?
Show answer
Book 5 is updated, because the id comes from the URL path. The 7 is ignored. BookRequest has no id component and Spring Boot's Jackson configuration does not fail on unknown properties, so the value never reaches the service.
Exercise
Why is it a mistake to reuse BookRequest as the body for a PATCH endpoint that changes only the title?
Show answer
BookRequest marks both title and author as @NotBlank. A PATCH body that omits author would fail validation with a 400. A PATCH needs its own request type in which fields may be absent, plus service logic that updates only the fields that were sent.