SteelReed

Search

Search posts, questions…

JPA & HibernateQuestion 14 / 24

Junior

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.

read, listwriteWhich job?projection recordonly needed columnsload entity, change fieldsservice maps to DTOreturn DTO from the API

3 points to say:

  1. Returning entities easily leaks fields like passwordHash.
  2. Projections for reads, entities for writes.
  3. @JsonIgnore is 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.