Why shouldn't you return JPA entities directly from an API? How do you use DTOs and projections?
Short answer
An entity is how data is stored, a response is a promise to the client; gluing them together causes data leaks, N+1 and infinite loops. Return a DTO (record), or query straight into a DTO with a projection.
3 points to say:
- Returning entities easily leaks fields like
passwordHash. - Projections for reads, entities for writes.
@JsonIgnoreis a patch; it does not separate the contract.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.