Sub topic 1
Why API Payloads Need DTOs
A REST endpoint exchanges JSON with clients, and your application stores data in JPA entities. It is tempting to use one class for both jobs, because the fields look the same. This chapter explains why that shortcut causes security holes, runtime errors, and brittle APIs, and what a data transfer object (DTO) changes. The later chapters in this tutorial show how to build DTOs as Java records.
Prerequisites
This chapter assumes you already know the following:
- Basic Java syntax and classes. Java 17 or later is installed.
- How to write a Spring Boot REST controller with
@RestControllerand@PostMapping. - What JSON, HTTP request bodies, and HTTP response bodies are.
- The basics of JPA entities, meaning a class annotated with
@Entitythat maps to a database table.
You do not need to know records yet. They appear briefly at the end as a preview.
What a DTO is
A data transfer object is a class whose only job is to carry data across a boundary. In a Spring Boot REST application, the boundary is the HTTP interface. A DTO describes exactly what a client may send or receive. It contains no persistence annotations and no business logic.
An entity describes how data is stored. A DTO describes how data is exchanged. These are two different concerns, and they change for different reasons. A database migration changes entities. A new client or a new API version changes DTOs.
What goes wrong when entities are the payload
Consider the common shortcut: the controller accepts an entity and returns an entity.
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private String email;
private String passwordHash;
private String role;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getPasswordHash() { return passwordHash; }
public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; }
public String getRole() { return role; }
public void setRole(String role) { this.role = role; }
}import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
class UserController {
private final UserRepository repository;
UserController(UserRepository repository) {
this.repository = repository;
}
@PostMapping
User create(@RequestBody User user) {
return repository.save(user);
}
}This compiles and works in a demo. It has at least five problems.
Sensitive fields leak out
Jackson, the JSON library Spring Boot uses, serializes every readable property by default. The response to the call above includes passwordHash and role. Anyone who can call the endpoint sees them. Adding a sensitive column to the table later exposes it automatically, with no code change in the controller. The default is "everything is public", and you have to remember to opt out field by field.
Clients can set fields they should not control
The same problem exists in the other direction. This request creates an administrator:
{"name": "Mallory", "email": "[email protected]", "role": "ADMIN"}Jackson calls setRole and setId because they exist. This is called mass assignment, or over-posting. The id field is also bindable. If a client sends an existing id, save may update another user's row instead of creating a new one. Server-controlled fields such as id, role, createdAt, and version should not be part of what a client can write.
The API is welded to the database schema
If the entity is the contract, renaming a column or splitting a table also renames or reshapes the JSON. Every client breaks. You lose the ability to refactor the database without a coordinated API change. The reverse also holds: an API that needs a field the database does not store, such as a computed displayName, forces you to add transient fields to the entity.
Serialization fights with JPA
Entities are managed objects. Their relationships are often lazy, which means related data is loaded on first access. Serializing an entity touches every getter, which triggers this loading at an unplanned time:
- Outside a transaction or session, Jackson hits an unloaded lazy association and you get a
LazyInitializationException. Hibernate proxies can also cause "No serializer found for class ByteBuddyInterceptor" errors. - Spring Boot enables
spring.jpa.open-in-viewby default. It keeps the session open during serialization, so the error disappears. Instead, each lazy association now runs its own query while the JSON is written. This is the N+1 query problem, and it is hidden inside the serializer. Boot logs a warning about this setting at startup. - Bidirectional relationships, such as
OrderholdingList<OrderLine>while eachOrderLinepoints back to itsOrder, make Jackson recurse until it fails with aStackOverflowErroror an infinite-recursionJsonMappingException.
One shape cannot serve every operation
A single entity has to answer different questions in different places:
| Operation | Fields the client sends | Fields the client receives |
|---|---|---|
| Create user | name, email, password | id, name, email |
| Update profile | name, email | id, name, email |
| Admin listing | none | id, name, email, role, status |
| Public profile | none | name only |
Validation rules differ too. A password is required when creating a user but absent from a profile update. If the entity carries all the validation annotations, you end up with groups or conditional logic. With separate DTOs, each shape carries only the rules that apply to it.
The DTO boundary
With DTOs, the controller never sees an entity. The service layer converts between the two representations.
Two kinds of DTO appear in this picture:
- A request DTO lists the fields a client is allowed to send. A field that is not declared cannot be bound.
- A response DTO lists the fields a client is allowed to see. A field that is not declared cannot leak.
This reverses the default. Instead of "everything is exposed unless hidden", the rule becomes "nothing is exposed unless declared". Adding a column to the entity changes nothing in the API until you deliberately add it to a DTO.
A first look at the fix
Here is the same endpoint using records as DTOs. Do not worry about the record syntax yet. The next chapter covers it. Focus on what each type declares.
public record CreateUserRequest(String name, String email, String password) {
}public record UserResponse(Long id, String name, String email) {
public static UserResponse from(User user) {
return new UserResponse(user.getId(), user.getName(), user.getEmail());
}
}import org.springframework.stereotype.Service;
@Service
class UserService {
private final UserRepository repository;
UserService(UserRepository repository) {
this.repository = repository;
}
UserResponse create(CreateUserRequest request) {
User user = new User();
user.setName(request.name());
user.setEmail(request.email());
user.setPasswordHash(hash(request.password()));
user.setRole("USER");
return UserResponse.from(repository.save(user));
}
private String hash(String rawPassword) {
// Placeholder. Use a PasswordEncoder bean in real code.
return "{noop}" + rawPassword;
}
}The security properties now come from the structure of the code:
CreateUserRequesthas noroleorid. If a client sends"role": "ADMIN", the field has nowhere to go. Whether Jackson ignores it or rejects it depends on theFAIL_ON_UNKNOWN_PROPERTIESsetting. Spring Boot disables that check by default, so unknown properties are ignored.- The service sets
roleitself. The client has no influence over it. UserResponsehas nopasswordHash. It cannot appear in the output, even if someone adds more columns toUser.UserResponse.fromis the single place where entity fields are copied into the API. A schema change shows up as a compile error or a one-line edit there.
Costs and trade-offs
DTOs are not free. Be clear about what you pay.
- More types. A resource with create, update, and read shapes needs three or more classes, plus mapping code. Records keep each one to a few lines, which is a large part of why they suit this role.
- Mapping code. Someone has to copy fields between entities and DTOs. You can write it by hand, as above, or use a generator such as MapStruct. Hand-written mapping is verbose but explicit, and the compiler checks it. Reflection-based mappers hide mistakes until runtime.
- Drift risk. If an entity gains a field and the response DTO does not, the API silently omits it. This is usually the safe failure direction, but a test should catch it when the field is meant to be exposed.
You can reasonably skip DTOs in a few cases:
- A throwaway prototype or internal script that no other team consumes.
- A read-only endpoint over a type that is already a plain value object with no persistence role.
Be cautious about the second case. A type that starts as a plain value object often becomes an entity later. Once it is part of a public API, changing it is costly.
Common mistakes
- Renaming the entity and calling it a DTO. Copying every entity field into a class with the same name and shape gives you the same leaks and the same coupling, with extra code. A DTO should be designed around what the client needs.
- Reusing one DTO for requests and responses. A single
UserDtowithidandpasswordfields means clients can send an id, and responses must null out the password. Use separate request and response types. - Hiding fields with
@JsonIgnoreon the entity. This works for one case, but it hardcodes one view of the entity into the persistence class. The next endpoint that needs a different view will contradict it. It also leaves the write side open unless you remember@JsonProperty(access = WRITE_ONLY)on each field. - Exposing entities in nested DTOs. A
OrderResponsethat holds aUserentity field brings every problem above back in through the side door. DTOs should contain only DTOs and simple values. - Mapping in the controller. Putting conversion in the controller spreads entity knowledge into the web layer. Keep it in the service or in a static factory on the DTO, so the controller deals only with DTOs.
What comes next
You now have the reasons for the boundary. The next chapters build the pieces. First you will see how records are declared and what the compiler generates for them. Then you will see how Jackson binds JSON to records, how to use them as controller bodies, and how Bean Validation applies to them. Later chapters cover mapping from entities, Spring Data projections, the limits of records, JSON customization, and testing.
Exercise
A controller method is declared as @PostMapping Order create(@RequestBody Order order), where Order is a JPA entity with a status field set by the server and a lazy List<OrderLine> collection whose elements point back to the order. Name three problems this design can cause and say how request and response DTOs would address each.
Show answer
First, mass assignment: a client can send "status": "SHIPPED" and Jackson will set it through the setter. A request DTO that omits status has nowhere to bind it, and the service sets the status itself. Second, lazy loading: serializing the returned entity touches the orderLines collection, which either throws LazyInitializationException or silently runs extra queries when open-in-view is on. A response DTO holds only the values the service chose to copy, so no lazy access happens during serialization. Third, infinite recursion: Order holds lines and each line points back to the order, so Jackson loops until it fails. A response DTO with a list of line DTOs that have no back reference has no cycle. Other valid answers include schema coupling and leaking internal columns.
Exercise
A teammate says: "I added @JsonIgnore to passwordHash on the entity, so we don't need a response DTO." Give one reason this is a weaker fix than a response DTO.
Show answer
@JsonIgnore on the entity applies to every endpoint, so it fixes one view of the data in the persistence class. It also protects only fields someone remembered to annotate. A new sensitive column is exposed by default until a developer adds the annotation. A response DTO reverses the default, because only declared fields can appear. Note also that @JsonIgnore on a field applies to both reading and writing, which can cause surprising behavior when you do want the field to be settable in some other flow.