Practice: the DAO pattern
50 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Layering bugs come from a few habits: SQL leaking out of the DAO, rules hiding inside DAOs, one record for every job, and list queries with no limit. Each has a short, reliable fix.
Mistake 1: JDBC leaking out of the DAO
A DAO is finished only when its callers never see SQL, Connection, ResultSet or SQLException. Example 1 writes the addresses DAO that way.
Example 1 · src/main/java/com/shoplite/dao/JdbcAddressDao.java
Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database
package com.shoplite.dao;
import com.shoplite.model.Address;
import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import java.util.Optional;
public class JdbcAddressDao implements AddressDao { private static final String SELECT = "SELECT address_id, customer_id, label, line1, city, state, pincode, is_default FROM addresses";
private final JdbcTransactionManager tx;
public JdbcAddressDao(JdbcTransactionManager tx) { this.tx = tx; }
@Override public List<Address> findByCustomer(int customerId) { String sql = SELECT + " WHERE customer_id = ? ORDER BY is_default DESC, address_id LIMIT 20"; try (ConnectionLease lease = tx.lease(); PreparedStatement ps = lease.connection().prepareStatement(sql)) { ps.setInt(1, customerId); List<Address> addresses = new ArrayList<>(); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { addresses.add(mapRow(rs)); } } return addresses; } catch (SQLException e) { throw new DataAccessException("Could not load addresses of customer " + customerId, e); } }
@Override public Optional<Address> findDefault(int customerId) { String sql = SELECT + " WHERE customer_id = ? AND is_default = TRUE"; try (ConnectionLease lease = tx.lease(); PreparedStatement ps = lease.connection().prepareStatement(sql)) { ps.setInt(1, customerId); try (ResultSet rs = ps.executeQuery()) { return rs.next() ? Optional.of(mapRow(rs)) : Optional.empty(); } } catch (SQLException e) { throw new DataAccessException("Could not load the default address of customer " + customerId, e); } }
private static Address mapRow(ResultSet rs) throws SQLException { return new Address(rs.getInt("address_id"), rs.getInt("customer_id"), rs.getString("label"), rs.getString("line1"), rs.getString("city"), rs.getString("state"), rs.getString("pincode"), rs.getBoolean("is_default")); }}6 Hostel, Pune (default) 7 Home, Pune 12 MG Road, Indiranagar none
What this code does
- Callers see only
Addressrecords, aListand anOptional. The SQL, theResultSetand theSQLExceptionstay inside this class. findByCustomerputs the default address first and breaks ties withaddress_id, and has aLIMIT, because no customer needs more than a handful of addresses.- Customer 8 (Imran) has no address, so
findDefaultreturns an emptyOptionaland the demo printsnone.
The usual leaks are a method that returns a ResultSet "for flexibility", a service that builds a WHERE clause and passes it in, and throws SQLException on DAO methods. The fix is the standard DAO shape: one interface in Java words, one JDBC class with prepared statements, a private row mapper, Optional or List results, and SQLException translated inside.
Find the bug
Find the leak
Each DAO interface lets JDBC escape. Tap the wrong line.
The addresses of one customer.
Round 1 of 2Mistake 2: business rules inside the DAO
A DAO that refuses a sale because stock is low, adds a discount, or decides which status an order may move to is doing the service's job. Example 2 moves a stock rule from the DAO to the service.
Example 2 · Moving a stock rule from the DAO to the service
import java.util.HashMap;import java.util.Map;
class OutOfStockException extends RuntimeException { OutOfStockException(String message) { super(message); }}
// Before: the DAO decides whether a sale is allowedclass RuleInDaoStore { final Map<Integer, Integer> stock = new HashMap<>(Map.of(7, 60, 8, 0));
void sell(int id, int qty) { int left = stock.get(id); if (left < qty) { throw new OutOfStockException("Only " + left + " left"); // a rule, in the DAO } stock.put(id, left - qty); }}
// After: the DAO only reads and writes...class ProductStore { final Map<Integer, Integer> stock = new HashMap<>(Map.of(7, 60, 8, 0));
int stockOf(int id) { return stock.get(id); }
void updateStock(int id, int newStock) { stock.put(id, newStock); }}
class SaleService { private final ProductStore store;
SaleService(ProductStore store) { this.store = store; }
void sell(int id, int qty) { if (qty < 1 || qty > 5) { throw new IllegalArgumentException("1 to 5 units per sale"); } int left = store.stockOf(id); if (left < qty) { throw new OutOfStockException("Only " + left + " left"); } store.updateStock(id, left - qty); }}
public class RuleMoveDemo { public static void main(String[] args) { RuleInDaoStore before = new RuleInDaoStore(); before.sell(7, 9); System.out.println("Before: sold 9, stock " + before.stock.get(7));
ProductStore store = new ProductStore(); SaleService service = new SaleService(store); int[][] sales = {{7, 2}, {7, 9}, {8, 1}}; for (int[] s : sales) { try { service.sell(s[0], s[1]); System.out.println("After: sold " + s[1] + " of " + s[0] + ", stock " + store.stockOf(s[0])); } catch (RuntimeException e) { System.out.println("After: refused " + s[1] + " of " + s[0] + ": " + e.getMessage()); } } }}Before: sold 9, stock 51 After: sold 2 of 7, stock 58 After: refused 9 of 7: 1 to 5 units per sale After: refused 1 of 8: Only 0 left
What this code does
- With the rule in the DAO, adding "1 to 5 units" means editing data access code, and every other DAO method that changes stock needs its own copy.
- In the service, all sale rules sit together and run before any write.
ProductStoreis now plain storage that any service can reuse.
A rule inside a DAO runs only for callers of that one DAO method, and testing it needs a database. Move the decision into a service: the DAO reads and writes exactly what it is told, and the service checks, calculates and throws domain exceptions. A quick test: if a DAO method contains an if that is not about SQL or null columns, it probably holds a rule.
Mistake 3: one record for every job
Using one record for every job forces fake ids, fake values and exposed columns. Example 3 gives each job its own shape: entity, input DTO and screen DTO.
Example 3 · One record per job: entity, input DTO, screen DTO
import java.time.LocalDateTime;
record Customer(int id, String fullName, String email, String phone, LocalDateTime createdAt) { // entity}
record NewCustomer(String fullName, String email, String phone) { // input DTO}
record CustomerListRow(int id, String name, int orders) { // screen DTO}
public class RecordShapesDemo { static Customer saved(NewCustomer in, int newId) { return new Customer(newId, in.fullName(), in.email(), in.phone(), LocalDateTime.of(2026, 10, 16, 9, 30)); }
public static void main(String[] args) { NewCustomer form = new NewCustomer("Neha Joshi", "neha.joshi@example.com", "9876543210"); Customer neha = saved(form, 9); CustomerListRow row = new CustomerListRow(neha.id(), neha.fullName(), 0);
System.out.println("Typed by the user: " + form); System.out.println("Stored row: " + neha); System.out.println("Admin list shows: " + row); }}Typed by the user: NewCustomer[fullName=Neha Joshi, email=neha.joshi@example.com, phone=9876543210] Stored row: Customer[id=9, fullName=Neha Joshi, email=neha.joshi@example.com, phone=9876543210, createdAt=2026-10-16T09:30] Admin list shows: CustomerListRow[id=9, name=Neha Joshi, orders=0]
What this code does
- The form has no id or date to fake, the entity has every column, and the list row has only what the admin screen shows, including a count no table stores.
- The phone number is in the entity but not in the list row, so the screen cannot leak it.
The Customer entity used as sign-up input forces a fake id; used as a report row it forces fake values in fields the query never read; handed to a screen it exposes every column. Use entities for table rows, input DTOs (no id) for what users type, and report or screen DTOs for what a query or screen needs. Mapping happens at the layer edges: rows to objects in the DAO, entities to DTOs in the service.
Mistake 4: list queries without limits or a stable order
A list method with no LIMIT works in testing and hurts in production. Example 4 shows a page count that does not round up.
Example 4 · A page count that does not round up
public class PageCountBugDemo { static int pagesWrong(long total, int size) { return (int) (total / size); // drops the last, partly full page }
static int pagesRight(long total, int size) { return (int) ((total + size - 1) / size); }
public static void main(String[] args) { long[] totals = {14, 15, 3}; for (long t : totals) { System.out.println(t + " rows, size 5: wrong " + pagesWrong(t, 5) + ", right " + pagesRight(t, 5)); } }}14 rows, size 5: wrong 2, right 3 15 rows, size 5: wrong 3, right 3 3 rows, size 5: wrong 0, right 1
What this code does
- With 14 products the wrong formula says 2 pages, so the menu never offers page 3 and the last four products are unreachable. With 3 rows it says 0 pages.
- Rounding up with whole numbers gives 3, 3 and 1. The bug hides whenever the total happens to be a multiple of the page size.
A paged method with an ORDER BY that has ties shows repeated or missing rows, and a page count that does not round up hides the last page. The checklist for every list query: LIMIT ? OFFSET ? (or a fixed limit), an ORDER BY ending in the primary key, a COUNT(*) for the total, page count rounded up, and page and size validated in the service.
Predict the output
How many pages?
The page size is 5. What does this formula say?
Round 1 of 2
14 rows.
Next step
Check your understanding
12 quick questions