Careeroza
Why DTOs
What is a DTO?
A DTO (Data Transfer Object) is a simple class that describes exactly what goes in or out of your API. Your entity describes how data is stored. They look similar at first, but they change for different reasons.
| Problem when you return entities | How a DTO solves it |
|---|---|
| Internal fields leak (cost price, supplier email, password hash) | The DTO only has the fields the client may see |
| Client can set fields it should not (id, createdAt, rating) | The request DTO has no such fields |
| Renaming a DB column breaks the mobile app | The DTO keeps the public name; only the mapper changes |
| Lazy JPA relations cause errors or huge JSON while serializing | The DTO holds plain values, no proxies |
| One shape for create, update and read | Separate CreateProductRequest, ProductResponse... |
The Flow
Client JSON ---> CreateProductRequest (DTO) --mapper--> Product (entity) ---> database
|
Client JSON <--- ProductResponse (DTO) <--mapper-- Product (entity) <--------'Tip: Rule of thumb: controllers speak DTOs, repositories speak entities, and the service (or a mapper) converts between them.