Skip to lesson

Entity classes vs DTOs

A screen needs an order's id, date and total, but no single table row has that shape. Should the app pass table rows everywhere, or objects shaped for each job?

An entity mirrors a table row

An entity is a class whose fields match the columns of one table: one object per row, with the row's id. Product, Customer and Order are ShopLite's entities.

ShopLite writes its entities as records in com.shoplite.model. Example 1 prints one row of each as an object.

Example 1 · src/main/java/com/shoplite/app/EntityDemo.java

Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database

EntityDemo.javaJava
package com.shoplite.app;
import com.shoplite.config.ConnectionFactory;import com.shoplite.config.DatabaseConfig;import com.shoplite.dao.JdbcCustomerDao;import com.shoplite.dao.JdbcOrderDao;import com.shoplite.dao.JdbcProductDao;import com.shoplite.dao.JdbcTransactionManager;
public class EntityDemo {
    public static void main(String[] args) {        JdbcTransactionManager tx = new JdbcTransactionManager(new ConnectionFactory(DatabaseConfig.load()));
        System.out.println(new JdbcProductDao(tx).findById(9).orElseThrow());        System.out.println(new JdbcCustomerDao(tx).findById(3).orElseThrow());        System.out.println(new JdbcOrderDao(tx).findById(4).orElseThrow());    }}
Output
Product[id=9, sku=BK-CLEAN, name=Clean Code, categoryId=5, price=499.00, stock=30, active=true]
Customer[id=3, fullName=Meena Iyer, email=meena.iyer@example.com, phone=null, createdAt=2026-06-02T09:05]
Order[id=4, customerId=3, addressId=4, status=CANCELLED, orderedAt=2026-07-21T22:10]

What this code does

  • Each line is one row of one table, printed by the record's toString. Every column has a field, and the id is there.
  • Meena's phone column is NULL, so the field is null. ordered_at became a LocalDateTime and status the enum value CANCELLED.

The field types follow the column types: DECIMAL becomes BigDecimal, DATETIME becomes LocalDateTime, a nullable column becomes a field that can be null, and the status text becomes an OrderStatus enum. The DAO for a table returns its entities.

Section 16 (JPA) uses the same word for classes marked @Entity. The idea is the same: one object per row.

A DTO carries exactly what a screen needs

A DTO (data transfer object) is a small record built for one use: a screen, a report or an input form. It is not tied to one table.

OrderSummary holds what the "My orders" screen shows: order id, date, status, item count and total. Example 2 builds it from entities and from one query, and counts the queries.

A products row becomes a Product entity with every column (the DAO maps it). The service maps it to a ProductCard DTO with only the name and price a screen needs. A JOIN and GROUP BY report query fills a SalesByCategory DTO directly, with no entity.

Example 2 · Entities and N+1 queries versus one DTO query

SummaryDemo.javaJava
import java.math.BigDecimal;import java.time.LocalDate;import java.util.ArrayList;import java.util.List;
enum Status { PLACED, SHIPPED, DELIVERED }
// Entities: one object per table rowrecord Order(int id, int customerId, LocalDate orderedOn, Status status) {}
record OrderItem(int orderId, int productId, int quantity, BigDecimal unitPrice) {}
// DTO: one object per line of the "My orders" screenrecord OrderSummary(int orderId, LocalDate orderedOn, Status status, int itemCount, BigDecimal total) {}
// Stands in for MySQL and counts the queriesclass FakeDatabase {    int queries = 0;    private final List<Order> orders = List.of(            new Order(2, 2, LocalDate.of(2026, 7, 5), Status.DELIVERED),            new Order(7, 2, LocalDate.of(2026, 8, 9), Status.DELIVERED),            new Order(14, 2, LocalDate.of(2026, 9, 21), Status.SHIPPED));    private final List<OrderItem> items = List.of(            new OrderItem(2, 9, 1, new BigDecimal("499.00")),            new OrderItem(2, 10, 1, new BigDecimal("650.00")),            new OrderItem(2, 11, 2, new BigDecimal("399.00")),            new OrderItem(7, 6, 1, new BigDecimal("1299.00")),            new OrderItem(7, 11, 1, new BigDecimal("399.00")),            new OrderItem(14, 1, 1, new BigDecimal("17999.00")),            new OrderItem(14, 6, 1, new BigDecimal("1299.00")));
    List<Order> findOrders(int customerId) {        queries++;        return orders.stream().filter(o -> o.customerId() == customerId).toList();    }
    List<OrderItem> findItems(int orderId) {        queries++;        return items.stream().filter(i -> i.orderId() == orderId).toList();    }
    List<OrderSummary> findSummaries(int customerId) {        queries++;        List<OrderSummary> result = new ArrayList<>();        for (Order o : orders) {            if (o.customerId() == customerId) {                result.add(summarise(o, items.stream().filter(i -> i.orderId() == o.id()).toList()));            }        }        return result;    }
    static OrderSummary summarise(Order o, List<OrderItem> its) {        BigDecimal total = BigDecimal.ZERO;        for (OrderItem i : its) {            total = total.add(i.unitPrice().multiply(BigDecimal.valueOf(i.quantity())));        }        return new OrderSummary(o.id(), o.orderedOn(), o.status(), its.size(), total);    }}
public class SummaryDemo {    public static void main(String[] args) {        FakeDatabase db = new FakeDatabase();
        List<OrderSummary> fromEntities = new ArrayList<>();        for (Order o : db.findOrders(2)) {            fromEntities.add(FakeDatabase.summarise(o, db.findItems(o.id())));        }        System.out.println("From entities: " + fromEntities.size() + " orders, " + db.queries + " queries");
        db.queries = 0;        List<OrderSummary> fromDto = db.findSummaries(2);        System.out.println("From DTO query: " + fromDto.size() + " orders, " + db.queries + " query");        fromDto.forEach(s -> System.out.println("  #" + s.orderId() + " " + s.status() + " Rs " + s.total()));    }}
Output
From entities: 3 orders, 4 queries
From DTO query: 3 orders, 1 query
  #2 DELIVERED Rs 1947.00
  #7 DELIVERED Rs 1698.00
  #14 SHIPPED Rs 19298.00

What this code does

  • Built from entities, the screen costs 1 query for the orders plus 1 per order for its items: 4 queries for 3 orders, 101 for 100 orders.
  • The DTO query returns the finished summaries in one go. Both ways give the same totals, which match the real ShopLite data for customer 2.

No single entity has that shape: the total comes from order_items, and the item count is a calculation. Building it from entities means loading every order and then every order's items, one query per order (the N+1 queries problem). A DTO filled by one GROUP BY query needs one round trip, however many orders there are.

Predict the output

How many queries?

Count the SQL queries a screen costs.

Round 1 of 2

The code loads 50 Order entities, then calls findItems(order) for each one.

List<Order> orders = db.findOrders(customerId);
for (Order o : orders) {
items.add(db.findItems(o.id()));
}

Report queries that map straight into DTO records

A report DTO is a record filled straight from a JOIN or GROUP BY query, such as SalesByCategory(category, unitsSold, revenue). Its rows match no table.

A report query joins and groups tables. Example 3 maps each result row straight into a SalesByCategory record, and Example 4 prints the report.

Example 3 · src/main/java/com/shoplite/dao/JdbcReportDao.java

Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database

JdbcReportDao.javaJava
package com.shoplite.dao;
import com.shoplite.model.SalesByCategory;
import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;
public class JdbcReportDao implements ReportDao {    private final JdbcTransactionManager tx;
    public JdbcReportDao(JdbcTransactionManager tx) {        this.tx = tx;    }
    @Override    public List<SalesByCategory> salesByCategory() {        String sql = """                SELECT c.name AS category,                       SUM(oi.quantity) AS units_sold,                       SUM(oi.quantity * oi.unit_price) AS revenue                FROM order_items oi                JOIN orders o ON o.order_id = oi.order_id                JOIN products p ON p.product_id = oi.product_id                JOIN categories c ON c.category_id = p.category_id                WHERE o.status <> 'CANCELLED'                GROUP BY c.name                ORDER BY revenue DESC                LIMIT 50""";        try (ConnectionLease lease = tx.lease();             PreparedStatement ps = lease.connection().prepareStatement(sql);             ResultSet rs = ps.executeQuery()) {            List<SalesByCategory> rows = new ArrayList<>();            while (rs.next()) {                rows.add(new SalesByCategory(rs.getString("category"), rs.getInt("units_sold"),                        rs.getBigDecimal("revenue")));            }            return rows;        } catch (SQLException e) {            throw new DataAccessException("Could not build the sales report", e);        }    }}
Output (ReportDemo in Example 4 calls it)
Sales by category:
  Laptops        3 units  Rs  150970.00
  Mobiles        4 units  Rs  126397.00
  Accessories    9 units  Rs   13941.00
  Fashion        6 units  Rs    8594.00
  Books         12 units  Rs    5741.00
Orders of customer 2:
  OrderSummary[orderId=14, orderedAt=2026-09-21T21:05, status=SHIPPED, itemCount=2, total=19298.00]
  OrderSummary[orderId=7, orderedAt=2026-08-09T11:00, status=DELIVERED, itemCount=2, total=1698.00]
  OrderSummary[orderId=2, orderedAt=2026-07-05T19:45, status=DELIVERED, itemCount=3, total=1947.00]

What this code does

  • One query joins four tables, skips cancelled orders and groups by category. Each result row becomes a SalesByCategory record; there is no entity in between.
  • The aliases units_sold and revenue are the column names the mapper reads. SUM(oi.quantity * oi.unit_price) is a DECIMAL, read with getBigDecimal.
  • The DAO uses JdbcTransactionManager.lease() to get its connection, the shape every DAO in the module project uses. The service-layer lesson explains it.

Example 4 · src/main/java/com/shoplite/app/ReportDemo.java

Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database

ReportDemo.javaJava
package com.shoplite.app;
import com.shoplite.config.ConnectionFactory;import com.shoplite.config.DatabaseConfig;import com.shoplite.dao.JdbcOrderDao;import com.shoplite.dao.JdbcReportDao;import com.shoplite.dao.JdbcTransactionManager;import com.shoplite.model.OrderSummary;import com.shoplite.model.SalesByCategory;
public class ReportDemo {
    public static void main(String[] args) {        JdbcTransactionManager tx = new JdbcTransactionManager(new ConnectionFactory(DatabaseConfig.load()));
        System.out.println("Sales by category:");        for (SalesByCategory row : new JdbcReportDao(tx).salesByCategory()) {            System.out.printf("  %-12s %3d units  Rs %10s%n", row.category(), row.unitsSold(), row.revenue());        }        System.out.println("Orders of customer 2:");        for (OrderSummary s : new JdbcOrderDao(tx).findSummariesByCustomer(2)) {            System.out.println("  " + s);        }    }}
Output (freshly loaded database)
Sales by category:
  Laptops        3 units  Rs  150970.00
  Mobiles        4 units  Rs  126397.00
  Accessories    9 units  Rs   13941.00
  Fashion        6 units  Rs    8594.00
  Books         12 units  Rs    5741.00
Orders of customer 2:
  OrderSummary[orderId=14, orderedAt=2026-09-21T21:05, status=SHIPPED, itemCount=2, total=19298.00]
  OrderSummary[orderId=7, orderedAt=2026-08-09T11:00, status=DELIVERED, itemCount=2, total=1698.00]
  OrderSummary[orderId=2, orderedAt=2026-07-05T19:45, status=DELIVERED, itemCount=3, total=1947.00]

What this code does

  • The first block comes from JdbcReportDao (Example 3). The second comes from JdbcOrderDao.findSummariesByCustomer, a GROUP BY query that fills OrderSummary records, newest order first.
  • The totals for customer 2 match Example 2. The real query does in one round trip what the entity approach needed four for.

The column aliases in the SQL (AS units_sold, AS revenue) become the names the mapper reads. Report DAOs return lists of DTOs and never entities, because a report row is not something you can update or delete.

Fix the error

Fix the report mapper

The query is SELECT ... SUM(oi.quantity) AS units_sold. Pick the line that reads it.

Read the units column of a report row.

return new SalesByCategory(
rs.getString("category"),
rs.getInt("units"),
rs.getBigDecimal("revenue"));

Error

java.sql.SQLException: Column 'units' not found.
Every report query still gets a LIMIT. A report that "always has 5 rows" today may have thousands once data grows.

Input DTOs: NewCustomer without an id

An input DTO is a record with what a user types to create something, and nothing the database fills in: NewCustomer(fullName, email, phone) has no id and no createdAt.

CustomerDao.save(NewCustomer) returns the full Customer entity. Example 5 compares it with a save that takes an entity with id 0.

Example 5 · Why an input DTO beats an entity with id 0

InputDtoDemo.javaJava
import java.util.HashMap;import java.util.Map;
record Customer(int id, String fullName, String email) {}
record NewCustomer(String fullName, String email) {}
// Takes an entity and trusts its id, as a cache or an "insert or update" method wouldclass SloppyCustomerStore {    final Map<Integer, Customer> rows = new HashMap<>();
    Customer save(Customer c) {        rows.put(c.id(), c);        return c;    }}
// Takes an input DTO: there is no id to get wrong, the store decides itclass CustomerStore {    final Map<Integer, Customer> rows = new HashMap<>();    private int nextId = 1;
    Customer save(NewCustomer input) {        Customer saved = new Customer(nextId++, input.fullName(), input.email());        rows.put(saved.id(), saved);        return saved;    }}
public class InputDtoDemo {    public static void main(String[] args) {        SloppyCustomerStore sloppy = new SloppyCustomerStore();        sloppy.save(new Customer(0, "Asha Rao", "asha.rao@example.com"));        sloppy.save(new Customer(0, "Ravi Kumar", "ravi.kumar@example.com"));        System.out.println("Entity with id 0: " + sloppy.rows.size() + " customer kept " + sloppy.rows.values());
        CustomerStore store = new CustomerStore();        Customer asha = store.save(new NewCustomer("Asha Rao", "asha.rao@example.com"));        Customer ravi = store.save(new NewCustomer("Ravi Kumar", "ravi.kumar@example.com"));        System.out.println("Input DTO: " + store.rows.size() + " customers, ids " + asha.id() + " and " + ravi.id());    }}
Output
Entity with id 0: 1 customer kept [Customer[id=0, fullName=Ravi Kumar, email=ravi.kumar@example.com]]
Input DTO: 2 customers, ids 1 and 2

What this code does

  • The sloppy store trusts the placeholder id 0, so Ravi silently replaces Asha. The caller had to invent an id that means nothing, and the store could not tell.
  • With NewCustomer there is no id field at all, so the caller cannot get it wrong. The store returns the real Customer entity with the id it chose.

The previous DAO lesson used save(Product) with id 0 as a shortcut. That forces every caller to invent placeholder values, and code cannot tell a saved object from an unsaved one. From here on ShopLite saves NewProduct and NewCustomer input DTOs, and the module project uses them.

Find the bug

Find the input bug

Each snippet saves a new customer badly. Tap the wrong line.

Create a customer from a sign-up form.

Round 1 of 2

Where mapping between entities and DTOs happens

Mapping is copying data from one shape to another, such as a ResultSet row to an entity, or an entity to a DTO. Each layer maps at its own edge.

No layer should see a shape it should not know about. Example 6 maps a Customer entity to a CustomerCard for the support desk.

Example 6 · The service maps an entity to a screen DTO

CustomerCardDemo.javaJava
import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.List;import java.util.Locale;
// Entity: every column, including private onesrecord Customer(int id, String fullName, String email, String phone, LocalDateTime createdAt) {}
// DTO for the support desk screen: only what the agent may seerecord CustomerCard(String name, String maskedEmail, String memberSince) {}
class CustomerService {    private static final DateTimeFormatter MONTH_YEAR = DateTimeFormatter.ofPattern("MMM yyyy", Locale.ENGLISH);
    CustomerCard toCard(Customer c) {        return new CustomerCard(c.fullName(), mask(c.email()), c.createdAt().format(MONTH_YEAR));    }
    private static String mask(String email) {        int at = email.indexOf('@');        return email.charAt(0) + "***" + email.substring(at);    }}
public class CustomerCardDemo {    public static void main(String[] args) {        List<Customer> customers = List.of(                new Customer(1, "Asha Rao", "asha.rao@example.com", "9876543201", LocalDateTime.of(2026, 5, 4, 10, 15)),                new Customer(3, "Meena Iyer", "meena.iyer@example.com", null, LocalDateTime.of(2026, 6, 2, 9, 5)));        CustomerService service = new CustomerService();
        for (Customer c : customers) {            CustomerCard card = service.toCard(c);            System.out.println(card.name() + " | " + card.maskedEmail() + " | member since " + card.memberSince());        }    }}
Output
Asha Rao | a***@example.com | member since May 2026
Meena Iyer | m***@example.com | member since Jun 2026

What this code does

  • The service turns the full Customer entity into a CustomerCard DTO. The phone number never leaves the service, so the screen cannot show it by mistake.
  • The app layer only prints the card. If the support desk later needs a new field, the DTO and the mapping change, not the entity or the table.

Who maps what:

  • DAO: ResultSet rows → entities or report DTOs. Nothing JDBC leaves the DAO.
  • Service: input DTOs → checked values for the DAO, and entities → result DTOs such as PlacedOrder or a public profile.
  • App: DTOs → text on the screen. It never builds SQL rows or entities by hand.
  • Never hand a whole entity to a screen that should not show every field, such as a phone number.

Order of execution

Follow a customer to the screen

Arrange the journey of one customer row, from first to last.

Next step

Check your understanding

12 quick questions