Skip to lesson

DAO interface and JDBC implementation

Right now every class that needs a product would write its own SQL, and every copy changes when the table does. A DAO puts that SQL in one place.

The ProductDao interface

A DAO interface lists what the program can do with one table, in Java terms and with no SQL, for example findById, save and delete.

ProductDao has five methods: find one product, find all, save a new one, update one and delete one. The comments say what save, update and delete return.

ProductDao.javaJava
public interface ProductDao {    Optional<Product> findById(int id);    List<Product> findAll();    Product save(Product product);      // returns a copy that has the generated id    boolean update(Product product);    // false when no row has that id    boolean delete(int id);             // false when no row has that id}

The interface knows nothing about JDBC: its types are Product, Optional and List, so any class can implement it later.

JdbcProductDao: prepared statements and a row mapper

A JDBC implementation is the class that carries out a DAO interface with JDBC: implements ProductDao, one method per operation, each with a PreparedStatement.

JdbcProductDao keeps all the SQL for the products table. The repeated work of reading a row goes into one private method, mapRow(ResultSet rs).

Example 1 · src/main/java/com/shoplite/dao/JdbcProductDao.java

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

JdbcProductDao.javaJava
package com.shoplite.dao;
import com.shoplite.config.ConnectionFactory;import com.shoplite.model.Product;
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;import java.util.Optional;
public class JdbcProductDao implements ProductDao {    private static final String SELECT =            "SELECT product_id, sku, name, category_id, price, stock, is_active FROM products";    private static final int ROW_IS_REFERENCED = 1451;
    private final ConnectionFactory connections;
    public JdbcProductDao(ConnectionFactory connections) {        this.connections = connections;    }
    @Override    public Optional<Product> findById(int id) {        try (Connection con = connections.getConnection();             PreparedStatement ps = con.prepareStatement(SELECT + " WHERE product_id = ?")) {            ps.setInt(1, id);            try (ResultSet rs = ps.executeQuery()) {                return rs.next() ? Optional.of(mapRow(rs)) : Optional.empty();            }        } catch (SQLException e) {            throw new DataAccessException("Could not load product " + id, e);        }    }
    @Override    public List<Product> findAll() {        try (Connection con = connections.getConnection();             PreparedStatement ps = con.prepareStatement(SELECT + " ORDER BY product_id");             ResultSet rs = ps.executeQuery()) {            List<Product> products = new ArrayList<>();            while (rs.next()) {                products.add(mapRow(rs));            }            return products;        } catch (SQLException e) {            throw new DataAccessException("Could not load products", e);        }    }
    @Override    public Product save(Product p) {        String sql = "INSERT INTO products (sku, name, category_id, price, stock, is_active) VALUES (?, ?, ?, ?, ?, ?)";        try (Connection con = connections.getConnection();             PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {            ps.setString(1, p.sku());            ps.setString(2, p.name());            ps.setInt(3, p.categoryId());            ps.setBigDecimal(4, p.price());            ps.setInt(5, p.stock());            ps.setBoolean(6, p.active());            ps.executeUpdate();            try (ResultSet keys = ps.getGeneratedKeys()) {                keys.next();                return new Product(keys.getInt(1), p.sku(), p.name(), p.categoryId(), p.price(), p.stock(), p.active());            }        } catch (SQLException e) {            throw new DataAccessException("Could not save product " + p.sku(), e);        }    }
    @Override    public boolean update(Product p) {        String sql = "UPDATE products SET sku = ?, name = ?, category_id = ?, price = ?, stock = ?, is_active = ?"                + " WHERE product_id = ?";        try (Connection con = connections.getConnection();             PreparedStatement ps = con.prepareStatement(sql)) {            ps.setString(1, p.sku());            ps.setString(2, p.name());            ps.setInt(3, p.categoryId());            ps.setBigDecimal(4, p.price());            ps.setInt(5, p.stock());            ps.setBoolean(6, p.active());            ps.setInt(7, p.id());            return ps.executeUpdate() == 1;        } catch (SQLException e) {            throw new DataAccessException("Could not update product " + p.id(), e);        }    }
    @Override    public boolean delete(int id) {        try (Connection con = connections.getConnection();             PreparedStatement ps = con.prepareStatement("DELETE FROM products WHERE product_id = ?")) {            ps.setInt(1, id);            return ps.executeUpdate() == 1;        } catch (SQLException e) {            if (e.getErrorCode() == ROW_IS_REFERENCED) {                throw new DataAccessException("Product " + id + " has orders and cannot be deleted", e);            }            throw new DataAccessException("Could not delete product " + id, e);        }    }
    private static Product mapRow(ResultSet rs) throws SQLException {        return new Product(                rs.getInt("product_id"),                rs.getString("sku"),                rs.getString("name"),                rs.getInt("category_id"),                rs.getBigDecimal("price"),                rs.getInt("stock"),                rs.getBoolean("is_active"));    }}
Output (ProductDaoDemo in Example 2 calls these methods)
Optional[Product[id=9, sku=BK-CLEAN, name=Clean Code, categoryId=5, price=499.00, stock=30, active=true]]
Optional.empty
All products: 15
Saved with id 16
Updated: true
Price now: 299.00
Deleted: true
Deleted again: false

What this code does

  • Every method follows one shape: open a connection and a PreparedStatement in try-with-resources, set the ? values, run it, map the result, and translate any SQLException.
  • mapRow is the only code that knows the column names. findById and findAll both use it, so they can never read a row differently.
  • save asks for Statement.RETURN_GENERATED_KEYS and builds a new Product with the id MySQL created.

Every query that returns products calls the row mapper, which reads the columns of the current row and builds a Product, so a new column is added in exactly one place.

Fix the error

Fix the DAO method

Each method fails at run time. Pick the replacement for the highlighted line.

Round 1 of 2

findById must return Optional.empty() for a missing id.

try (ResultSet rs = ps.executeQuery()) {
return Optional.of(mapRow(rs));
}

Error

java.sql.SQLException: Before start of result set
findAll without a limit is fine for 15 products. The paging lesson in this module replaces it before the table grows.

Optional for lookups, the saved entity for inserts

Example 2 uses the DAO with no SQL in sight: a lookup that finds nothing, an insert, an update and two deletes.

Example 2 · src/main/java/com/shoplite/app/ProductDaoDemo.java

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

ProductDaoDemo.javaJava
package com.shoplite.app;
import com.shoplite.config.ConnectionFactory;import com.shoplite.config.DatabaseConfig;import com.shoplite.dao.JdbcProductDao;import com.shoplite.dao.ProductDao;import com.shoplite.model.Product;
import java.math.BigDecimal;
public class ProductDaoDemo {
    public static void main(String[] args) {        ProductDao products = new JdbcProductDao(new ConnectionFactory(DatabaseConfig.load()));
        System.out.println(products.findById(9));        System.out.println(products.findById(99));        System.out.println("All products: " + products.findAll().size());
        Product wings = new Product(0, "BK-WINGS", "Wings of Fire", 5, new BigDecimal("350.00"), 25, true);        Product saved = products.save(wings);        System.out.println("Saved with id " + saved.id());
        Product cheaper = new Product(saved.id(), saved.sku(), saved.name(), saved.categoryId(),                new BigDecimal("299.00"), saved.stock(), saved.active());        System.out.println("Updated: " + products.update(cheaper));        System.out.println("Price now: " + products.findById(saved.id()).map(Product::price).orElseThrow());
        System.out.println("Deleted: " + products.delete(saved.id()));        System.out.println("Deleted again: " + products.delete(saved.id()));    }}
Output (freshly loaded database)
Optional[Product[id=9, sku=BK-CLEAN, name=Clean Code, categoryId=5, price=499.00, stock=30, active=true]]
Optional.empty
All products: 15
Saved with id 16
Updated: true
Price now: 299.00
Deleted: true
Deleted again: false

What this code does

  • The demo works only with ProductDao, Product and plain Java values. It has no SQL, no ResultSet and no try/catch for SQLException.
  • findById(99) returns Optional.empty, not null. save returns a product with id 16, the next AUTO_INCREMENT value on a freshly loaded database.
  • The second delete returns false: no row had that id any more, which is a normal answer, not an error.

findById returns Optional<Product>: the caller decides what a missing product means. save returns the saved entity, a copy of the record that carries the id MySQL generated, because records cannot change. update and delete return true when one row changed and false when no row had that id.

The return types follow one rule:

  • Lookup by id → Optional<T>; never null.
  • List → List<T>; an empty list when nothing matches, never null.
  • Insert → the saved object with its generated id.
  • Update or delete → boolean from executeUpdate() == 1.

Predict the output

What does the DAO return?

Fresh ShopLite database with 15 products. Pick what is printed.

Round 1 of 2

A lookup for an id that does not exist.

Optional<Product> p = products.findById(99);
System.out.println(p);

Connections from a ConnectionFactory in the constructor

The DAO receives a ConnectionFactory through its constructor and asks it for a connection in every method. It never calls DriverManager itself.

Java
// Wrong: settings and password copied into every DAO methodtry (Connection con = DriverManager.getConnection(        "jdbc:mysql://localhost:3306/shoplite", "root", "root123")) { ... }
// Right: the DAO is given its connection source onceConnectionFactory connections = new ConnectionFactory(DatabaseConfig.load());ProductDao products = new JdbcProductDao(connections);
// and each method opens and closes its own connectiontry (Connection con = connections.getConnection();     PreparedStatement ps = con.prepareStatement(sql)) { ... }

This matters for two reasons. The settings stay in one place (the config package and environment variables), not in every DAO. And when the next module replaces the factory with a connection pool, no DAO method changes.

Find the bug

Find the connection bug

Each snippet hides connection settings inside the DAO. Tap the wrong line.

A DAO method opens its connection.

Round 1 of 2

Translating SQLException inside the DAO

Exception translation means the DAO catches the checked SQLException and throws an unchecked DataAccessException with a clear message, keeping the original as its cause.

A DAO that lets throws SQLException escape forces every service and menu method to depend on JDBC. Examples 3 and 4 show the wrong way and the right way.

Example 3 · Swallowing versus translating an error

TranslateDemo.javaJava
import java.sql.SQLException;import java.util.Optional;
class DataAccessException extends RuntimeException {    DataAccessException(String message, Throwable cause) {        super(message, cause);    }}
class ProductLookup {    // Pretend the server is down: this is what the driver would throw    private String runQuery(int id) throws SQLException {        throw new SQLException("Communications link failure", "08S01");    }
    // Wrong: the error is swallowed and looks like "not found"    Optional<String> findNameSwallowing(int id) {        try {            return Optional.of(runQuery(id));        } catch (SQLException e) {            return Optional.empty();        }    }
    // Right: translated into an unchecked exception that keeps the cause    Optional<String> findName(int id) {        try {            return Optional.of(runQuery(id));        } catch (SQLException e) {            throw new DataAccessException("Could not load product " + id, e);        }    }}
public class TranslateDemo {    public static void main(String[] args) {        ProductLookup dao = new ProductLookup();
        System.out.println("Swallowed: " + dao.findNameSwallowing(9).orElse("product 9 not found"));
        try {            dao.findName(9);        } catch (DataAccessException e) {            SQLException cause = (SQLException) e.getCause();            System.out.println("Translated: " + e.getMessage());            System.out.println("  cause: " + cause.getSQLState() + " " + cause.getMessage());        }    }}
Output
Swallowed: product 9 not found
Translated: Could not load product 9
  cause: 08S01 Communications link failure

What this code does

  • The swallowing version tells the user "product 9 not found" while the real problem is that the database is unreachable. Nobody will look for the outage.
  • The translating version throws DataAccessException, which callers need not declare. getCause() still gives the original SQLException with SQL state 08S01 (connection failure) for the log.

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

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

DaoErrorsDemo.javaJava
package com.shoplite.app;
import com.shoplite.config.ConnectionFactory;import com.shoplite.config.DatabaseConfig;import com.shoplite.dao.DataAccessException;import com.shoplite.dao.JdbcProductDao;import com.shoplite.dao.ProductDao;import com.shoplite.model.Product;
import java.math.BigDecimal;import java.sql.SQLException;
public class DaoErrorsDemo {
    public static void main(String[] args) {        ProductDao products = new JdbcProductDao(new ConnectionFactory(DatabaseConfig.load()));
        try {            products.delete(1);                            // the Redmi phone has orders        } catch (DataAccessException e) {            report(e);        }        try {            products.save(new Product(0, "MOB-RN13", "Copy of Redmi", 2, new BigDecimal("999.00"), 1, true));        } catch (DataAccessException e) {            report(e);        }    }
    private static void report(DataAccessException e) {        System.out.println(e.getMessage());        SQLException cause = (SQLException) e.getCause();        System.out.println("  cause: error " + cause.getErrorCode() + ", state " + cause.getSQLState());        System.out.println("  " + cause.getMessage());    }}
Output
Product 1 has orders and cannot be deleted
  cause: error 1451, state 23000
  Cannot delete or update a parent row: a foreign key constraint fails (`shoplite`.`order_items`, CONSTRAINT `fk_order_items_product` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`))
Could not save product MOB-RN13
  cause: error 1062, state 23000
  Duplicate entry 'MOB-RN13' for key 'products.uq_products_sku'

What this code does

  • Deleting product 1 breaks the foreign key from order_items, so MySQL answers with error 1451. JdbcProductDao.delete recognises the code and throws a message a user can understand.
  • Saving a second MOB-RN13 breaks the unique SKU constraint (error 1062). This DAO has no special case for it yet, so the general message is used, and the cause still shows exactly which key failed.
  • Both errors have SQL state 23000, the class for constraint violations; the vendor code tells you which constraint kind it was.

Without translation, throws SQLException spreads to every service and menu method. Known error codes get their own message: MySQL error 1451 on delete means "other rows point to this one", so the DAO says the product has orders. Everything else gets a general message, and the cause still holds the full detail for the logs.

Find the bug

Find the translation bug

Each catch block handles a database error badly. Tap the wrong line.

The database server is down.

Round 1 of 2
Never turn a database error into Optional.empty() or false. A server that is down is not the same as a product that does not exist.

Next step

Check your understanding

12 quick questions