Video in progress
Why shouldn't you return a JPA entity directly from a REST controller, and what does a DTO give you?
An entity is the internal model, while the API is an external contract. If you return the entity, internal refactoring breaks the API, unneeded or sensitive fields leak out, and lazy associations cause extra queries or errors during JSON serialization. A DTO separates these two worlds.
📖 Answer
If you return an entity, you typically get these:
- the
Userentity haspasswordHash; one day you forget@JsonIgnoreand it goes out through the API; order.customer.orders.customer...: a bidirectional association causes infinite recursion or aLazyInitializationException;- Jackson calls the getters, each loads a lazy collection, and a single endpoint runs 40 SQL queries;
- you rename a column and the mobile app breaks.
With a DTO:
public record OrderView(Long id, String status, BigDecimal total, List<LineView> lines) {
static OrderView from(Order o) {
return new OrderView(o.getId(), o.getStatus().name(), o.total(),
o.lines().stream().map(LineView::from).toList());
}
}
@GetMapping("/orders/{id}")
OrderView get(@PathVariable Long id) { return OrderView.from(service.find(id)); }
Now the API exposes only the fields you chose, and the entity is free to change.
The same rule applies on the way in: don't accept @RequestBody Order, because a client could send id or status itself and do mass assignment. Write a separate CreateOrderRequest record.
Where mapping should live: in a small project a static factory on the DTO is enough; with many DTOs, use MapStruct, which generates code at compile time with no reflection.
Sign up to mark studied questions and save your progress.