Sub topic 1
Why API Payloads Need DTOs
Prerequisites
This chapter assumes you can read basic Java classes and have Java 17 or later installed. You should also know how a Spring Boot @RestController handles a @PostMapping, and what JSON request and response bodies look like. You don't need to know records or Bean Validation yet. Later chapters cover them.
What a DTO is
A DTO (data transfer object) is a class whose only job is to carry data across a boundary. In a REST API, that boundary is the HTTP request and response. The DTO describes what clients send and receive. It says nothing about how the data is stored.
An entity is the other kind of class you will see. It maps to a database table through JPA, and it often holds relationships, internal flags, and lazy-loaded state. The two classes can look alike at first. They change for different reasons.
The problem with exposing entities
Consider a JPA entity for a user:
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private String email;
private String passwordHash;
private boolean admin;
public Long getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
public String getPasswordHash() { return passwordHash; }
public boolean isAdmin() { return admin; }
public void setName(String name) { this.name = name; }
public void setEmail(String email) { this.email = email; }
public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; }
public void setAdmin(boolean admin) { this.admin = admin; }
}If a controller returns User directly, Jackson serializes every readable property. The response then includes passwordHash and admin. If the controller accepts User as a request body, a client can send "admin": true and the setter will be called. This is called mass assignment. Both mistakes are easy to make because nothing in the code looks wrong.
Exposing entities causes other problems too:
- Coupling. Renaming a column or field changes the public API and breaks clients.
- Lazy loading. Serializing an entity can touch lazy associations. That triggers extra queries or a
LazyInitializationExceptionafter the transaction has closed. - Cycles. Bidirectional relationships, such as an order that points to items that point back to the order, can recurse forever during serialization.
- One shape for every use. Creating a user, updating a user, and listing users usually need different fields. One entity cannot fit all three.
What DTOs give you
A DTO makes the API contract explicit. You list the fields a client may send or see, and nothing else crosses the boundary by accident.
| Concern | Entity returned directly | Separate DTO |
|---|---|---|
| Sensitive fields | Exposed unless hidden with annotations | Absent unless you add them |
| Database refactoring | Can break clients | Contained in the mapping code |
| Request validation | Mixed with persistence rules | Rules sit on the request shape |
| Different views of the same data | One shape for all | One DTO per use case |
Separate DTOs also let you validate input at the point where it enters the system. A request DTO can say "name is required" without forcing that rule onto every row the database ever holds.
The flow of a request
The diagram shows where the DTOs sit. The controller only deals in DTOs. The entity stays behind the service.
Why records fit
DTOs are mostly boilerplate when written as ordinary classes. Each needs fields, a constructor, getters, equals, hashCode, and toString. A Java record generates all of these from one line. A record's fields are also final, which suits a payload that should not change after it is read.
Here is the shape of the DTOs this tutorial builds toward:
public record UserResponse(Long id, String name, String email) {
}This record has no passwordHash and no admin flag. A client cannot receive them, and a request record with the same fields could not set them. The next chapter explains the syntax and what the compiler generates.
Costs to keep in mind
DTOs add classes and mapping code. For a small internal prototype, returning an entity may be acceptable. The cost is worth paying when the API is public, when entities hold sensitive or internal fields, or when the request and response shapes differ. The mapping step is also where you can forget to copy a field. Tests catch that, and a later chapter shows how.
Exercises
Exercise
A controller method returns a JPA User entity that has a passwordHash field and a public getter for it. What happens to that field in the JSON response, and how does a DTO prevent it?
Show answer
Jackson serializes every readable property, so passwordHash appears in the JSON. A response DTO that declares only id, name, and email has no such field, so it cannot be serialized.
Exercise
Name two problems besides data leaks that come from using an entity as a request or response body.
Show answer
Any two of these: API changes whenever the schema changes, lazy-loading errors during serialization, infinite recursion from bidirectional relationships, and a single shape that cannot suit create, update, and list operations.