Why mixing SQL with business logic hurts
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Your first JDBC program works, so you keep adding features to the same method. Soon one change breaks something else, and nothing can be tested without MySQL. Separate layers prevent that.
One method that does everything
A mixed method is one method that reads the request, opens a database connection, builds the SQL, applies the business rules and prints the answer.
Almost every first JDBC program looks like this, because it is the shortest path from idea to working code. Example 1 is a "Buy now" feature for ShopLite written that way.
Example 1 · src/main/java/com/shoplite/app/BuyNowMixed.java
Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database
package com.shoplite.app;
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;
/** The "before" version: one method checks input, runs SQL, applies rules and prints. */public class BuyNowMixed {
public static void main(String[] args) { buy(1, 1, 7, 2); // Asha buys 2 power banks buy(1, 1, 8, 1); // the mouse has 0 in stock buy(1, 1, 7, 9); // more than 5 units of one product }
static void buy(int customerId, int addressId, int productId, int quantity) { String url = System.getenv("DB_URL"); try (Connection con = DriverManager.getConnection(url, System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { con.setAutoCommit(false); String name; BigDecimal price; int stock; try (PreparedStatement ps = con.prepareStatement( "SELECT name, price, stock FROM products WHERE product_id = ? AND is_active = TRUE FOR UPDATE")) { ps.setInt(1, productId); try (ResultSet rs = ps.executeQuery()) { if (!rs.next()) { System.out.println("Sorry, no product " + productId); return; } name = rs.getString("name"); price = rs.getBigDecimal("price"); stock = rs.getInt("stock"); } } if (quantity > 5) { System.out.println("Sorry, at most 5 units of one product per order"); return; } if (stock < quantity) { System.out.println("Sorry, " + name + " is out of stock"); return; } try (PreparedStatement ps = con.prepareStatement( "UPDATE products SET stock = stock - ? WHERE product_id = ?")) { ps.setInt(1, quantity); ps.setInt(2, productId); ps.executeUpdate(); } int orderId; try (PreparedStatement ps = con.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(); orderId = keys.getInt(1); } } try (PreparedStatement ps = con.prepareStatement( "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, ?, ?)")) { ps.setInt(1, orderId); ps.setInt(2, productId); ps.setInt(3, quantity); ps.setBigDecimal(4, price); ps.executeUpdate(); } con.commit(); BigDecimal total = price.multiply(BigDecimal.valueOf(quantity)); System.out.println("Order #" + orderId + ": " + quantity + " x " + name + " = Rs " + total); } catch (SQLException e) { System.out.println("Something went wrong: " + e.getMessage()); } }}Order #17: 2 x Mi Power Bank 20000mAh = Rs 4398.00 Sorry, Logitech M331 Silent Mouse is out of stock Sorry, at most 5 units of one product per order
What this code does
- One
buymethod does six jobs: it opens the connection, locks and reads the product row, checks the 5-unit rule, checks the stock, writes to three tables and prints the receipt. - The business rules (
quantity > 5,stock < quantity) sit between SQL statements. Nothing outside this method can reuse them, and they run only after a connection is open. catch (SQLException e)prints a message and carries on, so the caller never learns that the order failed.
The method really works: it places an order in one transaction and refuses bad requests. The trouble starts when the program grows.
What goes wrong when SQL and rules are mixed
Example 2 only wants to see one rule work, "at most 5 units", while MySQL is stopped.
Example 2 · src/main/java/com/shoplite/app/QuantityRuleCheck.java
Runs in: the shoplite-console project with the MySQL server stopped
package com.shoplite.app;
/** All I want is to see the "at most 5 units" rule work. MySQL is stopped. */public class QuantityRuleCheck {
public static void main(String[] args) { System.out.println("Checking: 9 units must be refused"); BuyNowMixed.buy(1, 1, 7, 9); }}Checking: 9 units must be refused Something went wrong: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
What this code does
- The check only wants to see the 5-unit rule refuse 9 units. That rule needs no data, yet
buyopens a connection first, so with MySQL stopped the rule never runs. Communications link failureis the driver's message for "no server answered". With mixed code, every developer and every build machine needs a running database just to check oneif.
Mixed code is cheap to write and expensive to keep. Three problems appear as soon as a second feature arrives:
- Duplication. The cart, the product page and the stock report all need "read a product", so each copies the same
SELECTand the same row-reading lines. When one copy forgetsAND is_active = TRUE, a hidden product shows up on one screen only. - No tests without a database. The rule "at most 5 units" needs no data at all, but it sits after
getConnection, so checking it needs a running MySQL with the right rows, as Example 2 shows. - Changes ripple everywhere. Renaming a column means editing every copied query. Moving from a console to a web API (Section 14) means rewriting every method, because the printing is mixed into each one.
Four layers: app, service, DAO and model
A layer is a group of classes that does one kind of work, usually one package: talking to the user, applying business rules, or running SQL.
ShopLite uses four layers, one package each. Example 3 is the same "Buy now" feature split into them, with a Map standing in for MySQL.
Example 3 · The same feature in four layers
import java.math.BigDecimal;import java.util.HashMap;import java.util.Map;import java.util.Optional;
// model: plain datarecord Product(int id, String name, BigDecimal price, int stock) {}
record Receipt(int quantity, String productName, BigDecimal total) {}
// dao: the only class that knows where products are stored.// A Map stands in for MySQL here; the next lesson writes the JDBC version.class ProductStore { private final Map<Integer, Product> rows = new HashMap<>();
void add(Product p) { rows.put(p.id(), p); }
Optional<Product> findById(int id) { return Optional.ofNullable(rows.get(id)); }
void updateStock(int id, int newStock) { Product p = rows.get(id); rows.put(id, new Product(p.id(), p.name(), p.price(), newStock)); }}
class ShopRuleException extends RuntimeException { ShopRuleException(String message) { super(message); }}
class BuyService { private final ProductStore store;
BuyService(ProductStore store) { this.store = store; }
Receipt buy(int productId, int quantity) { if (quantity < 1 || quantity > 5) { throw new ShopRuleException("at most 5 units of one product per order"); } Product p = store.findById(productId) .orElseThrow(() -> new ShopRuleException("no product " + productId)); if (p.stock() < quantity) { throw new ShopRuleException(p.name() + " is out of stock"); } store.updateStock(p.id(), p.stock() - quantity); return new Receipt(quantity, p.name(), p.price().multiply(BigDecimal.valueOf(quantity))); }}
public class LayersDemo { public static void main(String[] args) { ProductStore store = new ProductStore(); store.add(new Product(7, "Mi Power Bank 20000mAh", new BigDecimal("2199.00"), 60)); store.add(new Product(8, "Logitech M331 Silent Mouse", new BigDecimal("849.00"), 0)); BuyService service = new BuyService(store);
int[][] requests = {{7, 2}, {8, 1}, {7, 9}}; for (int[] r : requests) { try { Receipt receipt = service.buy(r[0], r[1]); System.out.println(receipt.quantity() + " x " + receipt.productName() + " = Rs " + receipt.total()); } catch (ShopRuleException e) { System.out.println("Sorry, " + e.getMessage()); } } }}2 x Mi Power Bank 20000mAh = Rs 4398.00 Sorry, Logitech M331 Silent Mouse is out of stock Sorry, at most 5 units of one product per order
What this code does
- Each class has one job.
ProductStoreis the only one that knows where products live,BuyServiceholds every rule, andmainonly sends requests and prints answers. BuyServicereports a broken rule by throwingShopRuleException; it never prints. The same service could answer a web page or a test.- The rules now run with no database at all. When a JDBC DAO replaces the Map,
BuyServiceandmainstay exactly the same.
The four layers:
- app (
com.shoplite.app): reads input, calls a service and prints the result. No SQL and no business rules. - service (
com.shoplite.service): the business rules, such as "at most 5 units" and "enough stock". No SQL and no printing. - dao (
com.shoplite.dao): the SQL. A DAO (data access object) reads and writes one table and turns rows into Java objects. No rules and no printing. - model (
com.shoplite.model): plain data classes such asProductandOrder, used by every layer.
Predict the output
Which layer owns this code?
Pick the layer where each piece of code belongs.
Round 1 of 4
Showing the result to the user.
Each layer only calls the one below it
The layers form a one-way street: app → service → dao → database. Example 4 breaks it with a service that prints its answer.
Example 4 · Mistake: a service that prints its answer
import java.math.BigDecimal;import java.util.List;
record Item(String name, BigDecimal price, int quantity) {}
// Wrong layer: the service prints, so its answer is lost to every other callerclass PrintingCartService { void showTotal(List<Item> cart) { BigDecimal total = BigDecimal.ZERO; for (Item i : cart) { total = total.add(i.price().multiply(BigDecimal.valueOf(i.quantity()))); } System.out.println("Total: Rs " + total); }}
// Right layer: the service returns the value; the caller decides how to show itclass CartService { BigDecimal total(List<Item> cart) { BigDecimal total = BigDecimal.ZERO; for (Item i : cart) { total = total.add(i.price().multiply(BigDecimal.valueOf(i.quantity()))); } return total; }}
public class CartLayerDemo { public static void main(String[] args) { List<Item> cart = List.of( new Item("Clean Code", new BigDecimal("499.00"), 1), new Item("Atomic Habits", new BigDecimal("399.00"), 2));
new PrintingCartService().showTotal(cart); // nothing comes back to check
BigDecimal total = new CartService().total(cart); System.out.println("Console screen: Total Rs " + total); System.out.println("SMS text: Pay Rs " + total.toPlainString() + " on delivery"); System.out.println("Test: " + (total.equals(new BigDecimal("1297.00")) ? "PASS" : "FAIL")); }}Total: Rs 1297.00 Console screen: Total Rs 1297.00 SMS text: Pay Rs 1297.00 on delivery Test: PASS
What this code does
PrintingCartServicegives nothing back, so a test cannot check the total and an SMS or web screen cannot reuse it. Printing is the app layer's job.CartService.totalreturns aBigDecimal. The console, the SMS text and the test each use the same answer in their own way.
A layer may call the layer right below it and use the model classes, but it never calls upward and never skips a layer. This keeps every change local: a new column touches only the DAO, a new rule only the service, and a new screen only the app layer, which gets every rule for free because it must go through the service.
Find the bug
Find the layering bug
Each snippet breaks the one-way street. Tap the wrong line.
This code is in the app layer.
Round 1 of 3java.sql imports belong only in dao, System.out only in app, and business ifs only in service.Where each ShopLite class will live
Each layer is a package under src/main/java/com/shoplite. Example 5 lists the shoplite-console project at the end of this module.
Example 5 · The shoplite-console files, layer by layer
Runs in: the shoplite-console project at the end of this module
find src/main/java -name "*.java" | sortsrc/main/java/com/shoplite/app/ConsoleMenu.java src/main/java/com/shoplite/app/Main.java src/main/java/com/shoplite/config/ConnectionFactory.java src/main/java/com/shoplite/config/DatabaseConfig.java src/main/java/com/shoplite/dao/CategoryDao.java src/main/java/com/shoplite/dao/ConnectionLease.java src/main/java/com/shoplite/dao/CustomerDao.java src/main/java/com/shoplite/dao/DataAccessException.java src/main/java/com/shoplite/dao/DuplicateEmailException.java src/main/java/com/shoplite/dao/JdbcCategoryDao.java src/main/java/com/shoplite/dao/JdbcCustomerDao.java src/main/java/com/shoplite/dao/JdbcOrderDao.java src/main/java/com/shoplite/dao/JdbcProductDao.java src/main/java/com/shoplite/dao/JdbcTransactionManager.java src/main/java/com/shoplite/dao/OrderDao.java src/main/java/com/shoplite/dao/ProductDao.java src/main/java/com/shoplite/dao/TransactionManager.java src/main/java/com/shoplite/model/Category.java src/main/java/com/shoplite/model/Customer.java src/main/java/com/shoplite/model/NewCustomer.java src/main/java/com/shoplite/model/NewProduct.java src/main/java/com/shoplite/model/Order.java src/main/java/com/shoplite/model/OrderItem.java src/main/java/com/shoplite/model/OrderLine.java src/main/java/com/shoplite/model/OrderStatus.java src/main/java/com/shoplite/model/OrderSummary.java src/main/java/com/shoplite/model/Page.java src/main/java/com/shoplite/model/PlacedOrder.java src/main/java/com/shoplite/model/Product.java src/main/java/com/shoplite/service/CustomerNotFoundException.java src/main/java/com/shoplite/service/CustomerService.java src/main/java/com/shoplite/service/EmailAlreadyUsedException.java src/main/java/com/shoplite/service/InvalidInputException.java src/main/java/com/shoplite/service/OrderService.java src/main/java/com/shoplite/service/OutOfStockException.java src/main/java/com/shoplite/service/ProductNotFoundException.java src/main/java/com/shoplite/service/ProductService.java src/main/java/com/shoplite/service/ShopException.java
What this code does
- Interfaces such as
ProductDaosay what can be done with a table; classes such asJdbcProductDaodo it with SQL. Services depend only on the interfaces. Mainis the one place that creates objects and connects them: settings, then DAOs, then services, then the menu. Every other class receives what it needs.
Every class has an obvious home, and its folder tells you what it may and may not do. Two extra packages hold things that are not a layer of their own: config reads the database settings, and the test folder holds in-memory DAOs for testing services without MySQL.
find command in Git Bash. In Command Prompt, dir /s /b src\main\java\*.java lists the same files.Next step
Check your understanding
12 quick questions