Skip to lesson

Placing an order: stock update plus order insert

A customer orders three items. The order row, each item row and every stock reduction must be saved together, and if any product is short, the database must look exactly as it did before.

The steps of placing an order

An order transaction is one JDBC transaction that inserts the order row, reduces the stock and inserts the item row for every cart line, then commits. Any failure rolls everything back.

Placing an order is four kinds of work on one connection: insert the order row, then for each cart line read today's price, reduce the stock and insert the item row, and finally work out the total.

Java
conn.setAutoCommit(false);   // then, on this one connection:try {    int orderId = insertOrder(conn, customerId, addressId);        // 1. order row    BigDecimal total = BigDecimal.ZERO;    for (OrderLine line : lines) {        BigDecimal price = activePrice(conn, line.productId());    // 2. today's price        reduceStock(conn, line);                                   // 3. only if enough        insertItem(conn, orderId, line, price);                    // 4. item row        total = total.add(price.multiply(BigDecimal.valueOf(line.quantity())));    }    conn.commit();                                                 // then return id and total} catch (SQLException | RuntimeException e) {    conn.rollback();   // every step is undone, then the error goes up    throw e;}

The total is not a column in the ShopLite schema. It is the sum of quantity × unit price over the items, so it is computed from the items and returned to the caller. Storing it as well would keep the same fact twice, and the two copies could disagree.

The price comes from the products table inside the transaction, never from the client, because a price sent by a browser or an app could be wrong or tampered with. Prices are BigDecimal, so Rs 399.00 × 2 is exactly 798.00.

Order of execution

Order the steps of an order

Arrange the work of one order, from first to last.

The generated order id, reused for every item

A generated key is the AUTO_INCREMENT id that MySQL makes during an INSERT. JDBC returns it when you ask for Statement.RETURN_GENERATED_KEYS and read getGeneratedKeys().

Every item row must point to its order, so the order id has to be read right after the order INSERT and passed to each item INSERT.

Java
try (PreparedStatement ps = conn.prepareStatement(        "INSERT INTO orders (customer_id, address_id) VALUES (?, ?)",        Statement.RETURN_GENERATED_KEYS)) {    ps.setInt(1, customerId);    ps.setInt(2, addressId);    ps.executeUpdate();    try (ResultSet keys = ps.getGeneratedKeys()) {        keys.next();        return keys.getInt(1);   // the new order_id    }}

Reading the key works as in the Prepared Statements module. The id is real only inside the transaction until you commit. If the order is rolled back, MySQL does not reuse that number, so order ids can have gaps. That is normal and harmless; never use the id to count orders.

Reducing stock with a conditional UPDATE

A conditional UPDATE checks and changes in one statement, because its WHERE clause contains the rule, such as stock >= ?. If the rule fails, zero rows change.

UPDATE products SET stock = stock - ? WHERE product_id = ? AND stock >= ? changes one row when the stock is enough, and zero rows when it is not. Example 1 takes 3 iPhones, then asks for 50.

Example 1 · The row count tells you if there was enough stock

Runs in: a Maven project with the MySQL driver and the ShopLite database

StockCheckDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class StockCheckDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static int reduceStock(Connection conn, int productId, int quantity) throws SQLException {        String sql = "UPDATE products SET stock = stock - ? WHERE product_id = ? AND stock >= ?";        try (PreparedStatement ps = conn.prepareStatement(sql)) {            ps.setInt(1, quantity);            ps.setInt(2, productId);            ps.setInt(3, quantity);            return ps.executeUpdate();   // 1 = done, 0 = not enough stock        }    }
    static int stockOf(Connection conn, int productId) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("SELECT stock FROM products WHERE product_id = ?")) {            ps.setInt(1, productId);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getInt("stock");            }        }    }
    public static void main(String[] args) throws SQLException {        int iphone = 3;        try (Connection conn = connect()) {            System.out.println("iPhone stock: " + stockOf(conn, iphone));            conn.setAutoCommit(false);            try {                System.out.println("Take 3:  rows changed = " + reduceStock(conn, iphone, 3));                System.out.println("Stock inside the transaction: " + stockOf(conn, iphone));                System.out.println("Take 50: rows changed = " + reduceStock(conn, iphone, 50));            } finally {                conn.rollback();   // a demo: undo the change                conn.setAutoCommit(true);            }            System.out.println("iPhone stock after rollback: " + stockOf(conn, iphone));        }    }}
Output
iPhone stock: 8
Take 3:  rows changed = 1
Stock inside the transaction: 5
Take 50: rows changed = 0
iPhone stock after rollback: 8

What this code does

  • executeUpdate() returns 1 for "take 3": the WHERE clause matched and the stock became 5 inside the transaction.
  • For "take 50" the condition stock >= 50 is false, so it returns 0 and nothing changes. The demo rolls back at the end, so the iPhone stock is 8 again.

Example 2 · Mistake: ignoring the row count oversells

Runs in: a Maven project with the MySQL driver and the ShopLite database

IgnoredRowCountBug.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class IgnoredRowCountBug {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    public static void main(String[] args) throws SQLException {        int iphone = 3;        int quantity = 20;   // only 8 in stock        try (Connection conn = connect()) {            conn.setAutoCommit(false);            int orderId;            try (PreparedStatement ps = conn.prepareStatement(                    "INSERT INTO orders (customer_id, address_id) VALUES (2, 3)", Statement.RETURN_GENERATED_KEYS)) {                ps.executeUpdate();                try (ResultSet keys = ps.getGeneratedKeys()) {                    keys.next();                    orderId = keys.getInt(1);                }            }            try (PreparedStatement ps = conn.prepareStatement(                    "UPDATE products SET stock = stock - ? WHERE product_id = ? AND stock >= ?")) {                ps.setInt(1, quantity);                ps.setInt(2, iphone);                ps.setInt(3, quantity);                ps.executeUpdate();   // BUG: returns 0 here, and nobody looks at it            }            try (PreparedStatement ps = conn.prepareStatement(                    "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, ?, ?)")) {                ps.setInt(1, orderId);                ps.setInt(2, iphone);                ps.setInt(3, quantity);                ps.setBigDecimal(4, new BigDecimal("69900.00"));                ps.executeUpdate();            }            conn.commit();            System.out.println("Order saved with " + quantity + " iPhones");
            try (Statement st = conn.createStatement();                 ResultSet rs = st.executeQuery("SELECT stock FROM products WHERE product_id = 3")) {                rs.next();                System.out.println("iPhone stock: " + rs.getInt("stock"));            }
            // clean up the bad order so the demo can run again            try (PreparedStatement ps = conn.prepareStatement("DELETE FROM orders WHERE order_id = ?")) {                ps.setInt(1, orderId);                ps.executeUpdate();                conn.commit();            }        }    }}
Output
Order saved with 20 iPhones
iPhone stock: 8

What this code does

  • The UPDATE changes 0 rows because only 8 phones exist, but nobody reads the return value, so the item row for 20 phones is inserted and committed.
  • The stock still says 8 while an order for 20 exists. The program deletes this bad order at the end so you can run it again; real code must throw when the count is 0.

executeUpdate() returns that row count: 1 when the stock was enough, 0 when it was not. The database does the subtraction (stock - ?), so it always works on the current value. The row count is your only signal, and Example 2 shows what happens when code ignores it: the order is saved, the stock is not reduced, and 20 phones are promised from a stock of 8.

Predict the output

What does executeUpdate() return?

iPhone stock is 8. The statement is the conditional UPDATE above.

Round 1 of 3

Take 3 phones.

ps.setInt(1, 3);
ps.setInt(2, iphone);
ps.setInt(3, 3);
int rows = ps.executeUpdate();
The CHECK stock >= 0 in the ShopLite schema is a last safety net. The WHERE condition is what turns "not enough stock" into a clear, expected result.

Out of stock: throw, roll back, nothing is saved

When the row count is 0, the method throws an OutOfStockException. The exception reaches the catch block of placeOrder, which rolls back.

Example 3 · Placing an order, and refusing one

Runs in: a Maven project with the MySQL driver and the ShopLite database

PlaceOrderDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.List;
record OrderLine(int productId, int quantity) { }
record OrderReceipt(int orderId, BigDecimal total) { }
class OutOfStockException extends RuntimeException {    OutOfStockException(String productName, int available, int requested) {        super("Only " + available + " left of " + productName + " (you asked for " + requested + ")");    }}
class ProductNotFoundException extends RuntimeException {    ProductNotFoundException(int productId) {        super("product " + productId + " does not exist or is not for sale");    }}
public class PlaceOrderDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static OrderReceipt placeOrder(Connection conn, int customerId, int addressId, List<OrderLine> lines)            throws SQLException {        conn.setAutoCommit(false);        try {            int orderId = insertOrder(conn, customerId, addressId);            BigDecimal total = BigDecimal.ZERO;            for (OrderLine line : lines) {                BigDecimal price = activePrice(conn, line.productId());                reduceStock(conn, line);                insertItem(conn, orderId, line, price);                total = total.add(price.multiply(BigDecimal.valueOf(line.quantity())));            }            conn.commit();            return new OrderReceipt(orderId, total);        } catch (SQLException | RuntimeException e) {            conn.rollback();            throw e;        } finally {            conn.setAutoCommit(true);        }    }
    static int insertOrder(Connection conn, int customerId, int addressId) throws SQLException {        String sql = "INSERT INTO orders (customer_id, address_id) VALUES (?, ?)";        try (PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {            ps.setInt(1, customerId);            ps.setInt(2, addressId);            ps.executeUpdate();            try (ResultSet keys = ps.getGeneratedKeys()) {                keys.next();                return keys.getInt(1);            }        }    }
    static BigDecimal activePrice(Connection conn, int productId) throws SQLException {        String sql = "SELECT price FROM products WHERE product_id = ? AND is_active = TRUE";        try (PreparedStatement ps = conn.prepareStatement(sql)) {            ps.setInt(1, productId);            try (ResultSet rs = ps.executeQuery()) {                if (!rs.next()) {                    throw new ProductNotFoundException(productId);                }                return rs.getBigDecimal("price");            }        }    }
    static void reduceStock(Connection conn, OrderLine line) throws SQLException {        String sql = "UPDATE products SET stock = stock - ? WHERE product_id = ? AND stock >= ?";        try (PreparedStatement ps = conn.prepareStatement(sql)) {            ps.setInt(1, line.quantity());            ps.setInt(2, line.productId());            ps.setInt(3, line.quantity());            if (ps.executeUpdate() == 0) {   // 0 rows changed: not enough stock                throw outOfStock(conn, line.productId(), line.quantity());            }        }    }
    static void insertItem(Connection conn, int orderId, OrderLine line, BigDecimal price) throws SQLException {        String sql = "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, ?, ?)";        try (PreparedStatement ps = conn.prepareStatement(sql)) {            ps.setInt(1, orderId);            ps.setInt(2, line.productId());            ps.setInt(3, line.quantity());            ps.setBigDecimal(4, price);            ps.executeUpdate();        }    }
    // Called after the UPDATE changed 0 rows: builds a clear message with the name and the real stock    static OutOfStockException outOfStock(Connection conn, int productId, int requested) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("SELECT name, stock FROM products WHERE product_id = ?")) {            ps.setInt(1, productId);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return new OutOfStockException(rs.getString("name"), rs.getInt("stock"), requested);            }        }    }
    static int stockOf(Connection conn, int productId) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("SELECT stock FROM products WHERE product_id = ?")) {            ps.setInt(1, productId);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getInt("stock");            }        }    }
    static int countOrders(Connection conn) throws SQLException {        try (Statement st = conn.createStatement();             ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM orders")) {            rs.next();            return rs.getInt(1);        }    }
    public static void main(String[] args) throws SQLException {        try (Connection conn = connect()) {            // Priya (customer 5) orders 2 x Atomic Habits and 1 x Mi Power Bank to her hostel (address 6)            OrderReceipt receipt = placeOrder(conn, 5, 6, List.of(new OrderLine(11, 2), new OrderLine(7, 1)));            System.out.println("Order " + receipt.orderId() + " placed, total Rs " + receipt.total());
            int ordersBefore = countOrders(conn);            try {                placeOrder(conn, 2, 3, List.of(new OrderLine(1, 1), new OrderLine(3, 20)));            } catch (OutOfStockException e) {                System.out.println("Order refused: " + e.getMessage());            }            System.out.println("New orders after the refusal: " + (countOrders(conn) - ordersBefore));            System.out.println("Redmi stock: " + stockOf(conn, 1) + ", iPhone stock: " + stockOf(conn, 3));        }    }}
Sample output
Order 17 placed, total Rs 2997.00
Order refused: Only 8 left of iPhone 15 128GB (you asked for 20)
New orders after the refusal: 0
Redmi stock: 40, iPhone stock: 8

What this code does

  • Priya's order inserts the order row, reads each price, reduces stock with the conditional UPDATE and inserts the items; the total is 2 × 399.00 + 2199.00 = 2997.00.
  • Ravi's order reduces the Redmi stock first, then the iPhone line throws OutOfStockException. The rollback removes the order row and puts the Redmi back: no new order, stock 40 and 8.

Everything done so far disappears: the order row, the earlier item rows and the stock already taken for earlier lines. In Example 3 the Redmi line ran first and its stock went down by one, yet after the rollback the Redmi stock is 40 again. The message a customer reads is plain: "Only 8 left of iPhone 15 128GB (you asked for 20)".

A product that is missing or hidden (is_active = FALSE) gets the same treatment with a ProductNotFoundException.

Find the bug

Find the stock-check bug

Each snippet should refuse an order that is short of stock. Tap the wrong line.

Throw when there was not enough stock.

Round 1 of 2

Checking the result in MySQL

Trust, but check: after running the program, look at the tables in the MySQL client. Example 4 runs three queries with mysql -e.

Example 4 · Checking the tables in the MySQL client

Runs in: a Maven project with the MySQL driver and the ShopLite database

Terminal
mysql -u shoplite_app -p shoplite --table -e "  SELECT order_id, customer_id, status FROM orders ORDER BY order_id DESC LIMIT 2;  SELECT order_id, product_id, quantity, unit_price FROM order_items WHERE order_id = 17 ORDER BY product_id;  SELECT product_id, name, stock FROM products WHERE product_id IN (1, 3, 7, 11);"
Sample output
Enter password:
+----------+-------------+--------+
| order_id | customer_id | status |
+----------+-------------+--------+
|       17 |           5 | PLACED |
|       16 |           7 | PLACED |
+----------+-------------+--------+
+----------+------------+----------+------------+
| order_id | product_id | quantity | unit_price |
+----------+------------+----------+------------+
|       17 |          7 |        1 |    2199.00 |
|       17 |         11 |        2 |     399.00 |
+----------+------------+----------+------------+
+------------+------------------------+-------+
| product_id | name                   | stock |
+------------+------------------------+-------+
|          1 | Redmi Note 13 5G       |    40 |
|          3 | iPhone 15 128GB        |     8 |
|          7 | Mi Power Bank 20000mAh |    59 |
|         11 | Atomic Habits          |    48 |
+------------+------------------------+-------+

What this code does

  • Order 17 has exactly two item rows, with the prices of that day, and the refused order left no row: the newest order before 17 is 16 from the seed data.
  • Stock went down only for the two products Priya bought (Power Bank 60 → 59, Atomic Habits 50 → 48). Your order id will differ if you placed other orders before.

You should see exactly one new order with its items, lower stock for those products, and no trace of the refused order. Order 17 is Priya's order with two items, and the newest order before it is 16 from the seed data. The Redmi and iPhone stock are unchanged, and only the two bought products went down.

Next step

Check your understanding

10 quick questions