Repaso
EspaƱol
Spring, JPA & Java WebIntermediateSPR-23

Why use DTOs instead of exposing JPA entities directly in your API?

Options

  1. DTOs always compile faster than the entities do
  2. To control what the API exposes and keep it stable (Correct option)
  3. Entities cannot be serialized to JSON in any way
  4. 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.

Key terms

Practice this question in Repaso