Returning DTOs instead of entities
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's order list screen shows four values, but loading whole entities reads nine columns, builds 23 objects and can trigger lazy queries. A read endpoint should ask for exactly what its screen shows.
One constructor-expression query for a read endpoint
A constructor expression is select new fully.qualified.Record(a, b, c) in JPQL. Hibernate runs the SQL, then calls that constructor once per row with the selected values.
A read endpoint only shows values, so it can skip entities. Example 1 turns one joined query straight into OrderRow records.
Example 1 · A record and a constructor-expression query
Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)
// OrderRow.javapackage com.shoplite.lab.order;
import java.time.LocalDateTime;
public record OrderRow(Integer id, String customerName, OrderStatus status, LocalDateTime orderedAt) {}
// OrderRepository.java (fragment)@Query(""" select new com.shoplite.lab.order.OrderRow(o.id, c.fullName, o.status, o.orderedAt) from Order o join o.customer c order by o.id""")List<OrderRow> findOrderRows();
// LabDemos.java (fragment)public void dtoRows() { stats.clear(); List<OrderRow> rows = orders.findOrderRows(); rows.stream().limit(3).forEach(System.out::println); System.out.println("Rows: " + rows.size() + ", statements: " + stats.getPrepareStatementCount() + ", entities loaded: " + stats.getEntityLoadCount() + ", managed: " + em.unwrap(org.hibernate.Session.class).getStatistics().getEntityCount());}DEBUG SQL - select o1_0.order_id,c1_0.full_name,o1_0.status,o1_0.ordered_at from orders o1_0 join customers c1_0 on c1_0.customer_id=o1_0.customer_id order by o1_0.order_id OrderRow[id=1, customerName=Asha Rao, status=DELIVERED, orderedAt=2026-07-02T10:12] OrderRow[id=2, customerName=Ravi Kumar, status=DELIVERED, orderedAt=2026-07-05T19:45] OrderRow[id=3, customerName=Asha Rao, status=DELIVERED, orderedAt=2026-07-18T13:05] Rows: 16, statements: 1, entities loaded: 0, managed: 0
What this code does
- The SQL selects only the 4 columns the record needs, joined in one statement. Hibernate calls
new OrderRow(...)for each of the 16 rows. - Statistics show 0 entities loaded and 0 managed: nothing is tracked, and there is no proxy that could run a later query.
The class is usually a record whose components match the selected values in order and type. A read endpoint such as "list of orders with customer names" never changes the values, so it does not need managed entities. One DTO query with a join replaces the entity list, the fetch join and the mapping code, and it cannot cause N+1, because there are no proxies.
Two rules trip people up. The class name must be fully qualified ("Could not resolve class 'ProductCard'" otherwise), and the arguments must match a constructor exactly, in order; a swapped pair fails with "Missing constructor for type". Spring Data checks @Query methods at startup, so both errors stop the app before the first request, which is good.
Fix the error
Fix the constructor expression
Read the real error, then pick the line that fixes it.
Round 1 of 2
The class name is not fully qualified.
Error
Could not resolve class 'OrderRow' named for instantiation
Fewer columns and no dirty-checking snapshots
A managed entity is an entity object that the persistence context tracks. Hibernate keeps a snapshot of its loaded values, so that at flush it can compare and find what changed.
Entities cost more than the columns on a screen. Example 2 counts what the entity version and the DTO version load and manage for the same screen.
Example 2 · Entities vs DTOs for the same screen, measured
Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)
// OrderRepository.java (fragment): the entity version of the same screen@Query("select o from Order o join fetch o.customer order by o.id")List<Order> findAllWithCustomer();
// LabDemos.java (fragment): both run in @Transactional(readOnly = true)public void entityRows() { stats.clear(); List<Order> list = orders.findAllWithCustomer(); System.out.println("Rows: " + list.size() + ", statements: " + stats.getPrepareStatementCount() + ", entities loaded: " + stats.getEntityLoadCount() + ", managed: " + em.unwrap(org.hibernate.Session.class).getStatistics().getEntityCount());}
// terminaljava -jar target/perf-lab-0.0.1-SNAPSHOT.jar --lab.demo=dtoDEBUG SQL - select o1_0.order_id,o1_0.address_id,c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone,o1_0.ordered_at,o1_0.status from orders o1_0 join customers c1_0 on c1_0.customer_id=o1_0.customer_id order by o1_0.order_id Rows: 16, statements: 1, entities loaded: 23, managed: 23 DEBUG SQL - select o1_0.order_id,c1_0.full_name,o1_0.status,o1_0.ordered_at from orders o1_0 join customers c1_0 on c1_0.customer_id=o1_0.customer_id order by o1_0.order_id OrderRow[id=1, customerName=Asha Rao, status=DELIVERED, orderedAt=2026-07-02T10:12] OrderRow[id=2, customerName=Ravi Kumar, status=DELIVERED, orderedAt=2026-07-05T19:45] OrderRow[id=3, customerName=Asha Rao, status=DELIVERED, orderedAt=2026-07-18T13:05] Rows: 16, statements: 1, entities loaded: 0, managed: 0
What this code does
- Both versions need one statement. The entity version reads 9 columns per row and builds and manages 23 entities (16 orders + 7 customers); the DTO version reads 4 columns and manages none.
- With bigger tables and pages the gap grows: every unused column and every managed entity costs memory and time on every call.
Fewer columns: the DTO query of Example 1 selects 4 columns. The entity version selects every column of both tables, 9 here and far more on real tables with descriptions, addresses and audit fields, and each column is read from disk, sent over the network and turned into Java objects.
No snapshots: in Example 2 the entity version loaded and manages 23 entities (16 orders and 7 customers), the DTO version 0. @Transactional(readOnly = true) already tells Hibernate to skip snapshots, which helps, but the entities are still built, registered and kept until the transaction ends. A DTO query skips all of it.
Entity graph vs DTO query: when each one wins
A read endpoint is a method that only shows values and changes nothing: lists, search results, reports, dashboards and exports.
The choice depends on one question: does the method change data? Example 3 lets MySQL add up each order's items instead of Java.
Example 3 · Let the database add up: a DTO query with sum and group by
Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)
// OrderTotalRow.javapackage com.shoplite.lab.order;
import java.math.BigDecimal;
/** One line of the "orders with totals" report. */public record OrderTotalRow(Integer orderId, String customerName, OrderStatus status, long items, BigDecimal total) {}
// OrderRepository.java (fragment)@Query(""" select new com.shoplite.lab.order.OrderTotalRow( o.id, c.fullName, o.status, sum(i.quantity), sum(i.quantity * i.unitPrice)) from Order o join o.customer c join o.items i where o.status = :status group by o.id, c.fullName, o.status order by o.id""")List<OrderTotalRow> findTotalsByStatus(OrderStatus status);
// LabDemos.java (fragment)public void totals() { stats.clear(); orders.findTotalsByStatus(OrderStatus.DELIVERED).stream().limit(4).forEach(System.out::println); System.out.println("statements: " + stats.getPrepareStatementCount() + ", entities loaded: " + stats.getEntityLoadCount());}DEBUG SQL - select o1_0.order_id,c1_0.full_name,o1_0.status,sum(i1_0.quantity),sum((i1_0.quantity*i1_0.unit_price)) from orders o1_0 join customers c1_0 on c1_0.customer_id=o1_0.customer_id join order_items i1_0 on o1_0.order_id=i1_0.order_id where o1_0.status=? group by o1_0.order_id,c1_0.full_name,o1_0.status order by o1_0.order_id OrderTotalRow[orderId=1, customerName=Asha Rao, status=DELIVERED, items=3, total=21097.00] OrderTotalRow[orderId=2, customerName=Ravi Kumar, status=DELIVERED, items=4, total=1947.00] OrderTotalRow[orderId=3, customerName=Asha Rao, status=DELIVERED, items=2, total=43839.00] OrderTotalRow[orderId=5, customerName=Kabir Singh, status=DELIVERED, items=2, total=22198.00] statements: 1, entities loaded: 0
What this code does
- MySQL joins orders, customers and order_items, multiplies quantity by unit price and sums per order. One row per order comes back, already totalled.
- Order 1's total is 18499.00 + 2 × 1299.00 = 21097.00, computed in SQL.
sumover a DECIMAL column gives aBigDecimal, so money stays exact;sum(i.quantity)gives aLong, matched by thelong itemscomponent.
Use entities, with a fetch join or an entity graph, when the use case changes data or needs the entity's own logic. Placing or cancelling an order loads the order and its items as entities, calls order.cancel(), and lets dirty checking write the UPDATE; a DTO cannot be changed and saved.
Use a DTO query when the use case only reads, and whenever the database should do the work. Example 3 sums with sum and group by in SQL, where entities would move far more data just to add it up in Java. In a code review, ask "Does this method change anything?" If not, start with a DTO query.
Predict the output
Entity or DTO?
Pick the better way to load the data for each method.
Round 1 of 3
Which fits this method?
Entities stay in the service layer; controllers see records
A DTO (data transfer object) is a plain record that holds only the values one screen or response needs, such as OrderRow(id, customerName, status, orderedAt).
A DTO only helps if it is the only thing that leaves the service. Example 4 shows a controller that passes records through.
Example 4 · Service returns records, controller passes them on
Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)
// OrderReportService.java (fragment)/** Read endpoint: one SELECT with only the needed columns, no entities. */public List<OrderRow> orderRows() { return orders.findOrderRows();}
// OrderLabController.java (fragment)@GetMapping("/lab/order-rows")java.util.List<com.shoplite.lab.order.OrderRow> orderRows() { return reports.orderRows();}
// terminal (shoplite.sql-count=true logs SQL statements per request)curl -i localhost:8080/lab/order-rowsHTTP/1.1 200
Content-Type: application/json
Content-Length: 1474
Date: Fri, 16 Oct 2026 08:09:48 GMT
[{"id":1,"customerName":"Asha Rao","status":"DELIVERED","orderedAt":"2026-07-02T10:12:00"},{"id":2,"customerName":"Ravi Kumar","status":"DELIVERED","orderedAt":"2026-07-05T19:45:00"},{"id":3,"customerName":"Asha Rao","status":"DELIVERED","orderedAt":"2026-07-18T13:05:00"},{"id":4,"customerName":"Meena Iyer","status":"CANCELLED","orderedAt":"2026-07-21T22:10:00"},{"id":5,"customerName":"Kabir Singh","status":"DELIVERED","orderedAt":"2026-07-28T09:30:00"},{"id":6,"customerName":"Priya Sharma","status":"DELIVERED","orderedAt":"2026-08-03T17:20:00"},{"id":7,"customerName":"Ravi Kumar","status":"DELIVERED","orderedAt":"2026-08-09T11:00:00"},{"id":8,"customerName":"Arjun Mehta","status":"DELIVERED","orderedAt":"2026-08-15T20:35:00"},{"id":9,"customerName":"Divya Nair","status":"DELIVERED ...
(server log)
DEBUG SQL - select o1_0.order_id,c1_0.full_name,o1_0.status,o1_0.ordered_at from orders o1_0 join customers c1_0 on c1_0.customer_id=o1_0.customer_id order by o1_0.order_id
INFO SqlCountConfig - GET /lab/order-rows -> 1 SQL statements (1 select)What this code does
- The controller never sees an
Order. Jackson writes the records' components, so the JSON has exactly the fields ofOrderRow. - The per-request counter (from the Counting Queries lesson) confirms 1 SQL statement for the whole request.
The layering rule of ShopLite: repositories return entities or DTO records, services work with entities inside a transaction and return records, and controllers only ever receive records. An entity never crosses the service boundary.
This rule makes the performance fixes stick. If a controller gets an entity, any lazy getter that it or Jackson calls runs SQL outside the service, where nobody counted it. With records nothing lazy is left, and the whole request of Example 4 costs one statement. The next lesson turns off Open Session in View, which makes a broken rule a hard error instead of a silent cost.
Find the bug
Find the leaking entity
Each method lets an entity cross the service boundary. Tap that line.
A controller method.
Round 1 of 2Next step
Check your understanding
11 quick questions