Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

When would you load entities, and when DTO projections, in a service? Give a rule your team can follow.

Our rule: load entities when the use case will change them, because only managed entities get dirty checking, optimistic locking, cascades and entity invariants; use DTO projections for everything read-only, such as lists, detail views, exports and reports. Never load a large entity graph just to copy a few fields into a DTO, and move complex reads to a dedicated query layer such as JdbcClient, jOOQ or a database view. We check the rule with SQL logs: queries per request and columns per query.

Why this question is asked

Teams argue about this constantly, and without a rule each developer picks whatever is closest to hand, which is usually findById() and a mapper. The result is services that load hundreds of columns to show ten, and lazy loading problems that appear in every layer. Interviewers ask for a rule because a senior engineer should be able to turn a set of trade-offs into a decision that a whole team can apply in code review. In this answer, we will recap what an entity gives us that a DTO does not, set out the write rule and the read rule with examples, look at the mapping anti-pattern, see where a dedicated query layer fits, and finish with how to measure whether the rule is followed.

1What a Managed Entity Gives Us

When Hibernate loads an entity, it puts it in the persistence context and keeps a snapshot of its state. At flush, it compares each managed entity with its snapshot and writes the differences. This is dirty checking. If the entity has a @Version field, every update includes a version check, which is optimistic locking: if someone else changed the row since we read it, our update fails instead of overwriting their change. Cascades propagate operations to children, and methods on the entity can protect its rules, such as an order that refuses new lines once shipped.

All of this is valuable when we change data. When we only read, it is pure cost: snapshots use memory, flush has to compare every loaded entity, and lazy associations can trigger queries anywhere the entity travels.

2Rule 1: Load Entities When You Will Change Them

If the use case modifies state, load the entity, call its methods and let the transaction commit. The entity is the right tool because we want its invariants, its version check and its cascades. We load only the aggregate we need, with a fetch join if the change needs children, and the entity does not leave the service.

Java
@Transactional
public void addLine(long orderId, AddLine cmd) {
Order order = orders.findWithLinesById(orderId).orElseThrow(); // entity, managed
order.addLine(cmd.productId(), cmd.quantity()); // rule: refuses if shipped
} // flush: insert into order_line ..., update orders set version = 8 where id = ? and version = 7

Notice that we never call save(). The entity is managed, so dirty checking writes the change at commit, and the version condition protects against a concurrent update.

3Rule 2: Use DTO Projections for Read-Only Views

If the use case only reads, return a projection shaped for the caller: a record DTO from a constructor expression, an interface projection, or a query into a view model. We select exactly the columns the screen shows, join exactly what it needs, and get unmanaged objects without snapshots. Lazy loading problems disappear because there is nothing lazy to load.

Java
public record OrderRow(long id, String customerName, BigDecimal total, OrderStatus status) {}
@Query("""
select new com.example.OrderRow(o.id, c.name, o.total, o.status)
from Order o join o.customer c
where o.createdAt >= :since order by o.createdAt desc""")
List<OrderRow> recentOrders(@Param("since") Instant since, Pageable page);
// one query, 4 columns, 50 rows; nothing added to the persistence context
The team rule at a glance
Use caseLoadWhy
Change state (commands)Entity, only the aggregate neededdirty checking, @Version, cascades, invariants
List or search screenDTO projectionfew columns, no snapshots, pageable
Detail view, read onlyDTO projection or fetch-joined queryexactly the fields shown
Export or reportQuery layer (JdbcClient, jOOQ, view)large, complex, set-based reads
Read then change in one callEntitythe change needs the managed state

4Avoid Mapping Large Graphs Into DTOs

A common pattern breaks both rules at once: load entities, then map them to DTOs with MapStruct or a hand-written mapper. For a single entity it is fine. For a list, the mapper touches associations, each touch triggers a lazy query, and we get N+1 queries plus full entity cost for a read-only result.

Java
// Anti-pattern: 50 orders, then a lazy load per order for the customer and the lines
List<OrderRow> rows = orderRepo.findTop50ByOrderByCreatedAtDesc().stream()
.map(mapper::toRow) // touches o.getCustomer().getName() and o.getLines()
.toList();
// SQL: 1 select for orders + 50 selects for customers + 50 for lines = 101 queries

The projection query in the previous section returns the same rows in one query. So the rule is not just use DTOs; it is let the query produce the DTO, instead of producing entities and converting them afterwards.

5Where a Dedicated Query Layer Fits

Some reads do not fit JPQL well: reports with grouping and window functions, dashboards that join eight tables, exports of millions of rows. For those, we allow a query layer next to the repositories. Spring's JdbcClient gives plain SQL with simple mapping to records, jOOQ gives type-safe SQL generated from the schema, and a database view or materialized view can hold a complicated join so the application reads it like a table. These tools are explicit about the SQL, which is exactly what we want for complex reads.

The boundary is simple to review: commands go through entities and repositories, reads go through projections or the query layer, and both live in the service that owns the data.

6Measuring That the Rule Holds

A rule nobody checks drifts. We log SQL in tests and count statements per request with Hibernate statistics or datasource-proxy, and add assertions for key endpoints: the order list must run 2 queries or fewer, for example. In code review, a findAll() followed by a mapper on a list endpoint is a flag. In production, query count per request and columns selected (visible in the SQL log or in pg_stat_statements text) tell us where entities are being loaded for reads.

7Follow-up questions

Does readOnly = true make loading entities for reads cheap enough?

It helps: with Spring and Hibernate, a read-only transaction sets the session to read-only, so Hibernate can skip snapshots and dirty checking (check your version). But we still load every column and eager association, and lazy associations still cause extra queries, so a projection remains cheaper for lists.

What about reading and then deciding whether to change?

Load the entity. If the decision needs the managed state, for example a version check or an invariant on the aggregate, the entity is the right tool even if most calls end without a change.

Should DTOs be shared between the API and the repository?

Small services often use one record for both and that is fine. When the API contract needs to evolve independently, keep a separate API type and map from the projection, which is cheap because both are flat.

8Conclusion

In this answer, we built a rule a team can follow. Load entities when the use case changes state, because only managed entities give dirty checking, optimistic locking, cascades and invariants. Use DTO projections for read-only lists, views and reports, and let the query produce the DTO instead of mapping loaded entity graphs. Send complex reads to a dedicated query layer such as JdbcClient, jOOQ or views, and verify the rule with SQL logs and query counts.

What to say in the interviewAbout 80 seconds aloud

Open with

My rule is simple: entities for writes, projections for reads. If the use case changes state, I load the entity, only the aggregate I need, because then I get dirty checking, optimistic locking with the version column, cascades and the entity's own invariants, and I let the transaction commit it.

Then, if they want more

If the use case only reads, like a list, a search, a detail screen or a report, I return a DTO projection, usually a record from a JPQL constructor expression, selecting only the columns the caller needs. That means fewer columns, no snapshots in the persistence context and no lazy loading surprises in other layers.

The anti-pattern I watch for in reviews is loading a list of entities and mapping them to DTOs, because the mapper touches associations and you get N+1 queries for a read-only result; the query should produce the DTO directly.

For complex reads such as reports with grouping or many joins, I would allow a dedicated query layer, JdbcClient, jOOQ or a database view, because explicit SQL is clearer there. And I verify the rule with SQL logs and statement counts per request in tests, rather than trusting it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "When would you load entities, and when DTO projections, in a service? Give a rule your...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/dcc42ec9e4/