Database-backed catalog project
What you will learn
A small inventory repository combines prepared statements, domain validation, database constraints and transaction ownership. The project is staged for a disposable PostgreSQL 17 database and does not connect to any database here.
- Explain the catalog and reservation schema.
- Implement a repository with guarded decrement and rollback boundary.
- Design an integration test matrix for constraints, rollback and cleanup.
Prerequisite: Java exceptions, interfaces, Optional and testing fundamentals. Database execution is NOT RUN; local JDK-only examples and test doubles are checked separately.
Disposable PostgreSQL schema
-- PostgreSQL 17 teaching schema. Disposable empty database only.CREATE TABLE catalog_item ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, sku varchar(40) NOT NULL UNIQUE, stock integer NOT NULL CHECK (stock >= 0));CREATE TABLE reservation ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, sku varchar(40) NOT NULL REFERENCES catalog_item(sku), quantity integer NOT NULL CHECK (quantity > 0));Source-reviewed PostgreSQL 17 DDL; NOT RUN. Contains identity, primary key, unique, check and foreign-key constraints.
Schema and domain
The catalog stores a unique non-null SKU and nonnegative stock. Reservation records positive quantities and references an existing SKU. The database enforces constraints independently of application checks. A migration principal creates the schema; an application principal should have only required operations. An actual migration tool, exact server patch and compatible JDBC driver are still to be selected and approved. Do not run these statements against an existing database.
Repository contract
Catalog receives DataSource through its constructor. find returns an Optional item, add validates nonnegative stock, reserve rejects nonpositive quantities before obtaining a connection. Within a single transaction, a guarded UPDATE must affect exactly one row before the INSERT. Failure raises SQLException and triggers rollback attempt. This does not distinguish missing SKU from insufficient stock; that is a deliberate small contract. Use an explicit service result if the caller needs to distinguish them.
Integration acceptance
Start from a fresh disposable schema. Add PEN with stock 5; find returns 5; a duplicate SKU must fail with SQLState 23505. Reserve 2, then query stock 3 and one reservation; attempt reserve 4 and observe no change. In another isolated test add a test-only CHECK constraint that rejects quantity 2, attempt reserve 2 from stock 5, then inspect state from a fresh connection: stock 5 and no reservation. Verify generated keys, apostrophe values, resource closure and concurrent requests with controlled barriers. These are expected results, not observed database outcomes. Pool sizing, migration automation and production concurrency are later topics.
Complete catalog repository
import java.sql.*;import java.util.*;import javax.sql.DataSource;
public final class Catalog { private final DataSource source; public Catalog(DataSource source) { this.source = Objects.requireNonNull(source); } public record Item(String sku, int stock) {}
public Optional<Item> find(String sku) throws SQLException { try (Connection c = source.getConnection(); PreparedStatement p = c.prepareStatement( "SELECT sku, stock FROM catalog_item WHERE sku = ?")) { p.setString(1, Objects.requireNonNull(sku)); try (ResultSet r = p.executeQuery()) { return r.next() ? Optional.of(new Item(r.getString("sku"), r.getInt("stock"))) : Optional.empty(); } } }
public long add(String sku, int stock) throws SQLException { if (stock < 0) throw new IllegalArgumentException("negative stock"); try (Connection c = source.getConnection(); PreparedStatement p = c.prepareStatement( "INSERT INTO catalog_item(sku, stock) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS)) { p.setString(1, Objects.requireNonNull(sku)); p.setInt(2, stock); if (p.executeUpdate() != 1) throw new SQLException("insert count"); try (ResultSet keys = p.getGeneratedKeys()) { if (!keys.next()) throw new SQLException("missing generated key"); return keys.getLong(1); } } }
public void reserve(String sku, int quantity) throws SQLException { if (quantity <= 0) throw new IllegalArgumentException("positive quantity required"); Objects.requireNonNull(sku); try (Connection c = source.getConnection()) { Tx.run(c, () -> { try (PreparedStatement p = c.prepareStatement( "UPDATE catalog_item SET stock = stock - ? WHERE sku = ? AND stock >= ?")) { p.setInt(1, quantity); p.setString(2, sku); p.setInt(3, quantity); if (p.executeUpdate() != 1) throw new SQLException("missing item or insufficient stock"); } try (PreparedStatement p = c.prepareStatement( "INSERT INTO reservation(sku, quantity) VALUES (?, ?)")) { p.setString(1, sku); p.setInt(2, quantity); if (p.executeUpdate() != 1) throw new SQLException("reservation count"); } }); } }}Compiled alongside Tx.java; database integration NOT RUN. See lab-fixtures/jdbc/v27-catalog for complete source, probe and integration plan.
Transaction helper for repository
import java.sql.Connection;import java.sql.SQLException;
public final class Tx { private Tx() {} @FunctionalInterface public interface Work { void run() throws SQLException; }
// Requires a freshly borrowed connection in auto-commit mode. // Caller closes it; do not reuse it after a failed rollback. public static void run(Connection c, Work work) throws SQLException { if (!c.getAutoCommit()) throw new SQLException("transaction already active or configured"); c.setAutoCommit(false); try { work.run(); c.commit(); } catch (SQLException | RuntimeException | Error failure) { try { c.rollback(); } catch (SQLException rollbackFailure) { failure.addSuppressed(rollbackFailure); } throw failure; } // No setAutoCommit(true) on failure: it could commit unfinished work. // The owning caller must close; a pool must reset/discard appropriately. }}Compiled and call-order tested without a server. Real transaction state and cleanup depend on the driver and pool.
Common mistakes
Do not use a production database for training, equate a proxy with database behavior, assume generated keys or SQL dialects are portable, or publish private credentials.
Practice
Write a five-case integration plan for a disposable catalog: create, absent lookup, duplicate, successful reservation, and failed reservation after the decrement. Include independent state observations and cleanup.
Use the manual practice hints; explain your reasoning before consulting the private review solution.
Official reading: constraints · states · connection · prepared · result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Database-backed catalog project — knowledge check
JDBC knowledge check.
Which constraint prevents duplicate SKU?
Why guard the stock update with stock >= quantity?
What must a zero affected-row count trigger?
How should real rollback be verified?
Where may the schema be applied for this lab?