Why use DTOs instead of exposing JPA entities directly in your API?
Options
- DTOs always compile faster than the entities do
- To control what the API exposes and keep it stable (Correct option)
- Entities cannot be serialized to JSON in any way
- Spring requires DTOs for every controller method
Answer
To control exactly what leaves/enters the API (no password hashes or internal fields), avoid lazy-loading surprises and keep the API stable when the database changes
Why
A DTO (Data Transfer Object) is a simple class (often a record) shaped for the API.
If you return an entity: you may leak sensitive fields, JSON serialization may trigger lazy loading (or fail), and any database change breaks your API contract.
With DTOs, the API and the database can evolve separately. Mapping is done by hand or with MapStruct.
Remember
Entity = database shape. DTO = API shape.