DTO mapping approaches
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
convert between entities and DTOs and choose how.
Planned topics
- A DTO (data transfer object) is the shape sent over the API. An entity is the internal model.
- Keeping them separate lets you change one without breaking the other and hides internal fields.
- Plain code: a
toResponse()method or a static mapper. Simple, explicit, easy to debug. - Mapper library (for example MapStruct): generates mapping code from interfaces; less typing for large models, with a learning cost.
- For small models prefer plain code; for many similar mappings a library pays off. Be ready to justify.
Draft outline details
Demonstration
record ProductResponse(long id, String name, long priceCents) {
static ProductResponse from(Product p) {
return new ProductResponse(p.getId(), p.getName(), p.getPriceCents());
}
}Check your understanding
Why not return the entity directly?
Show answer
It exposes internal fields and ties the API to the model.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.