Video in progress

Strong Junior 🌱 Spring

Why is it better to return a DTO instead of an entity in an API response?

An entity is the database structure, a DTO is the API contract. If you return the entity directly, sensitive fields leak out, lazy associations cause errors or extra queries, and every database change breaks the API.

📖 Answer

Try returning an entity like this:

@Entity
class User {
    Long id;
    String name;
    String passwordHash;           // leaks into the JSON!
    @OneToMany(mappedBy = "user")
    List<Order> orders;            // lazy: LazyInitializationException or N+1
}
  • passwordHash and internal statuses go to the client. You can patch it with @JsonIgnore, but one forgotten field is enough.
  • Jackson tries to serialize orders: if the session is closed — an error, if it's open — hidden queries.
  • User → Order → User — infinite JSON.
  • You renamed a column in the table — the mobile app broke.

With a DTO:

public record UserDto(long id, String name, int orderCount) {
    static UserDto of(User u, int count) { return new UserDto(u.getId(), u.getName(), count); }
}

The API shows only what's needed, and it doesn't budge when the database changes. Use separate DTOs for incoming requests too — otherwise a client can send role or balance and change it (mass assignment).