A service layer on top of DAOs
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Placing an order touches several tables, and every rule about it must apply whichever screen asks. Where do the rules live, and who decides where the transaction starts and ends?
Business rules live in services
A business rule is a decision the shop makes, not the database: "a name is required", "an email can be registered only once", "at most 5 units of one product".
CustomerService cleans the input, checks it, asks CustomerDao whether the email is taken, and only then saves. The code below sends four sign-ups through it.
CustomerService customers = new CustomerService(new JdbcCustomerDao(tx));NewCustomer[] inputs = { new NewCustomer(" Neha Joshi ", "Neha.Joshi@Example.com", "9876543210"), new NewCustomer("Neha J", "neha.joshi@example.com", ""), new NewCustomer("Rohan Das", "rohan.das@example", ""), new NewCustomer("Rohan Das", "rohan.das@example.com", "12345"),};for (NewCustomer input : inputs) { try { Customer c = customers.register(input); System.out.println("Registered #" + c.id() + " " + c.fullName() + " <" + c.email() + ">"); } catch (ShopException e) { System.out.println("Refused: " + e.getMessage()); }}Example 1 · src/main/java/com/shoplite/service/CustomerService.java
Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database
package com.shoplite.service;
import com.shoplite.dao.CustomerDao;import com.shoplite.dao.DuplicateEmailException;import com.shoplite.model.Customer;import com.shoplite.model.NewCustomer;
import java.util.Locale;
public class CustomerService { private final CustomerDao customerDao;
public CustomerService(CustomerDao customerDao) { this.customerDao = customerDao; }
public Customer register(NewCustomer input) { String name = input.fullName() == null ? "" : input.fullName().trim(); if (name.isEmpty()) { throw new InvalidInputException("Name is required"); } String email = input.email() == null ? "" : input.email().trim().toLowerCase(Locale.ROOT); if (!email.matches("[^@\\s]+@[^@\\s]+\\.[^@\\s]+")) { throw new InvalidInputException("Not a valid email: " + input.email()); } String phone = input.phone() == null || input.phone().isBlank() ? null : input.phone().trim(); if (phone != null && !phone.matches("[6-9]\\d{9}")) { throw new InvalidInputException("Phone must be 10 digits starting with 6, 7, 8 or 9"); } if (customerDao.findByEmail(email).isPresent()) { throw new EmailAlreadyUsedException(email); } try { return customerDao.save(new NewCustomer(name, email, phone)); } catch (DuplicateEmailException e) { // someone signed up with it a moment ago throw new EmailAlreadyUsedException(email); } }
public Customer getCustomer(int id) { return customerDao.findById(id).orElseThrow(() -> new CustomerNotFoundException(id)); }}Registered #9 Neha Joshi <neha.joshi@example.com> Refused: Email already registered: neha.joshi@example.com Refused: Not a valid email: rohan.das@example Refused: Phone must be 10 digits starting with 6, 7, 8 or 9
What this code does
- Validation comes first and needs no database: the trimmed name, the lower-cased email and the phone pattern. A bad input never reaches MySQL.
- The second sign-up differs only in letter case. Because the service lower-cases every email before checking and saving,
findByEmailfinds Neha and the duplicate is refused. - The service throws
InvalidInputExceptionorEmailAlreadyUsedException; it never prints. The demo loop decides how to show them.
Rules come in three kinds. Validation checks the input itself (format, range). Checks against data need a DAO call (is the email free, is there enough stock). Calculations produce new values (an order total). All three belong in the service, so every screen that registers a customer gets them.
Predict the output
Which kind of rule is it?
Pick the kind of business rule each piece of code applies.
Round 1 of 3
The email must look like an email.
UNIQUE constraint in MySQL is the real guard, so the service also turns the DAO's DuplicateEmailException into the same message.Constructor injection: wired once in Main
Constructor injection means a class receives the objects it needs through its constructor instead of creating them with new inside.
OrderService asks for a TransactionManager, a CustomerDao, a ProductDao and an OrderDao; it never builds them. Example 2 is Main, the one place that creates and connects everything.
Example 2 · src/main/java/com/shoplite/app/Main.java
Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database
package com.shoplite.app;
import com.shoplite.config.ConnectionFactory;import com.shoplite.config.DatabaseConfig;import com.shoplite.dao.JdbcCategoryDao;import com.shoplite.dao.JdbcCustomerDao;import com.shoplite.dao.JdbcOrderDao;import com.shoplite.dao.JdbcProductDao;import com.shoplite.dao.JdbcTransactionManager;import com.shoplite.service.CustomerService;import com.shoplite.service.OrderService;import com.shoplite.service.ProductService;
import java.util.Scanner;
/** The one place where every object is created and connected. */public class Main {
public static void main(String[] args) { ConnectionFactory connections = new ConnectionFactory(DatabaseConfig.load()); JdbcTransactionManager tx = new JdbcTransactionManager(connections);
JdbcProductDao productDao = new JdbcProductDao(tx); JdbcCategoryDao categoryDao = new JdbcCategoryDao(tx); JdbcCustomerDao customerDao = new JdbcCustomerDao(tx); JdbcOrderDao orderDao = new JdbcOrderDao(tx);
ProductService productService = new ProductService(productDao, categoryDao); CustomerService customerService = new CustomerService(customerDao); OrderService orderService = new OrderService(tx, customerDao, productDao, orderDao);
new ConsoleMenu(new Scanner(System.in), productService, customerService, orderService).run(); }}=== ShopLite === 1. Browse products 2. Register customer 3. Place order 4. Order history 0. Exit Choose: 0 Bye
What this code does
- Objects are created in dependency order. One
JdbcTransactionManageris shared by all four DAOs, andOrderServicegets the same one, so its transactions and its DAOs use the same connection. - This is the only class that names
Jdbc...classes. Services and the menu see only interfaces and other services, so the wiring here is the one place to change when an implementation changes.
Wiring is creating all those objects once and passing them in, in dependency order. In ShopLite only Main does this. Every other class just declares what it needs, which is what makes swapping a DAO (two lessons from now) a one-line change.
Order of execution
Wire ShopLite in order
Arrange what Main creates, so each object exists before the one that needs it.
private final fields and depend on interfaces (ProductDao), never on JdbcProductDao.Transactions that span several DAOs
Placing an order writes to three tables through two DAOs, so it must be one transaction on one connection. Example 3 shows what happens when each DAO opens its own.
Example 3 · src/main/java/com/shoplite/app/BrokenOrderDemo.java
Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database
package com.shoplite.app;
import com.shoplite.config.ConnectionFactory;import com.shoplite.config.DatabaseConfig;import com.shoplite.dao.DataAccessException;import com.shoplite.dao.JdbcOrderDao;import com.shoplite.dao.JdbcTransactionManager;import com.shoplite.dao.OrderDao;import com.shoplite.model.OrderItem;
import java.math.BigDecimal;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.List;
public class BrokenOrderDemo {
public static void main(String[] args) throws SQLException { ConnectionFactory connections = new ConnectionFactory(DatabaseConfig.load()); JdbcTransactionManager tx = new JdbcTransactionManager(connections); OrderDao orderDao = new JdbcOrderDao(tx); List<OrderItem> badItems = List.of(new OrderItem(999, 1, new BigDecimal("10.00"))); // no product 999
System.out.println("Orders at start: " + countOrders(connections)); try { int orderId = orderDao.create(1, 1); // its own connection, saved at once orderDao.addItems(orderId, badItems); // another connection: fails } catch (DataAccessException e) { System.out.println("Failed: " + e.getMessage()); } System.out.println("Orders after, no transaction: " + countOrders(connections));
try { tx.inTransaction(() -> { int orderId = orderDao.create(1, 1); orderDao.addItems(orderId, badItems); return orderId; }); } catch (DataAccessException e) { System.out.println("Failed: " + e.getMessage()); } System.out.println("Orders after, in a transaction: " + countOrders(connections)); }
private static int countOrders(ConnectionFactory connections) throws SQLException { try (Connection con = connections.getConnection(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM orders")) { rs.next(); return rs.getInt(1); } }}Orders at start: 16 Failed: Could not save items of order 17 Orders after, no transaction: 17 Failed: Could not save items of order 18 Orders after, in a transaction: 17
What this code does
- Without a transaction,
createruns on its own connection and is committed at once.addItemsfails on product 999 (a foreign key error), and order 17 stays behind with no items. - Inside
tx.inTransaction, both calls share one connection. The failure rolls back the order insert too, so the count stays at 17: nothing from the second attempt was saved. - Order id 18 was used and then rolled back. MySQL does not reuse an
AUTO_INCREMENTvalue, so gaps in ids are normal.
The DAOs of the previous lessons each open their own connection with auto-commit on, so the order row is saved, the items fail, and a half-finished order stays in the database. Passing a Connection into every DAO method would fix it, but then every service method handles JDBC objects, which is exactly what the layers were meant to avoid.
A TransactionManager that commits or rolls back
A TransactionManager is a small interface with one method, inTransaction(work). The JDBC version opens one connection, runs the work, commits, and rolls back if the work throws.
While the work runs, the connection is kept in a ThreadLocal, and DAOs ask tx.lease() for it. Example 4 is the JDBC version.
// A connection lent to a DAO: closed only if the DAO opened itpublic record ConnectionLease(Connection connection, boolean closeWhenDone) implements AutoCloseable { @Override public void close() throws SQLException { if (closeWhenDone) { connection.close(); } }}
// Every DAO method gets its connection like thistry (ConnectionLease lease = tx.lease(); PreparedStatement ps = lease.connection().prepareStatement(sql)) { ... }Example 4 · src/main/java/com/shoplite/dao/JdbcTransactionManager.java
Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database
package com.shoplite.dao;
import com.shoplite.config.ConnectionFactory;
import java.sql.Connection;import java.sql.SQLException;import java.util.function.Supplier;
/** Shares one connection with every DAO called inside inTransaction, on the same thread. */public class JdbcTransactionManager implements TransactionManager { private final ConnectionFactory connections; private final ThreadLocal<Connection> current = new ThreadLocal<>();
public JdbcTransactionManager(ConnectionFactory connections) { this.connections = connections; }
/** Inside a transaction: its connection. Outside: a new connection the DAO closes. */ public ConnectionLease lease() throws SQLException { Connection active = current.get(); if (active != null) { return new ConnectionLease(active, false); } return new ConnectionLease(connections.getConnection(), true); }
@Override public <T> T inTransaction(Supplier<T> work) { if (current.get() != null) { return work.get(); // already in one: join it } try (Connection con = connections.getConnection()) { con.setAutoCommit(false); current.set(con); try { T result = work.get(); con.commit(); return result; } catch (RuntimeException | SQLException e) { rollback(con, e); throw e; } finally { current.remove(); con.setAutoCommit(true); } } catch (SQLException e) { throw new DataAccessException("Transaction failed", e); } }
private static void rollback(Connection con, Exception original) { try { con.rollback(); } catch (SQLException e) { original.addSuppressed(e); } }}Orders at start: 16 Failed: Could not save items of order 17 Orders after, no transaction: 17 Failed: Could not save items of order 18 Orders after, in a transaction: 17
What this code does
inTransactionfollows the commit/rollback pattern from the transactions module: auto-commit off, work, commit; on anyRuntimeException(or aSQLExceptionfrom commit) roll back and throw the same exception on.currentis theThreadLocalthat letslease()hand the same connection to every DAO on this thread. Thefinallyblock clears it and turns auto-commit back on before the connection is closed.- If
inTransactionis called while a transaction is already running, the work simply joins the outer one. A service method can then call another transactional service method safely.
A ThreadLocal is a variable in which each thread sees its own value. Inside a transaction a DAO gets the shared connection, and closing the lease does nothing; outside a transaction it gets a fresh connection that the lease closes. So DAO methods keep their usual try-with-resources shape.
Predict the output
Is the order saved?
Both DAO calls run inside tx.inTransaction.
Round 1 of 2
The work throws before it finishes.
@Transactional (Section 16) works the same way inside: it binds one connection to the current thread for the length of the method.Domain exceptions: the service throws, the app explains
A domain exception names a broken business rule in the shop's own words, such as OutOfStockException or InvalidInputException. Its message is written for the user.
The service throws domain exceptions and never prints. The app layer catches them and shows the message, as the two catch blocks of the menu below do.
try { switch (choice) { case "1" -> browse(); case "2" -> register(); case "3" -> placeOrder(); case "4" -> history(); default -> System.out.println("Please choose 0 to 4"); }} catch (ShopException e) { System.out.println("Sorry: " + e.getMessage());} catch (DataAccessException e) { System.out.println("Database problem: " + e.getMessage() + ". Please try again.");}Example 5 · src/main/java/com/shoplite/service/OrderService.java
Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database
package com.shoplite.service;
import com.shoplite.dao.CustomerDao;import com.shoplite.dao.OrderDao;import com.shoplite.dao.ProductDao;import com.shoplite.dao.TransactionManager;import com.shoplite.model.OrderItem;import com.shoplite.model.OrderLine;import com.shoplite.model.OrderSummary;import com.shoplite.model.PlacedOrder;import com.shoplite.model.Product;
import java.math.BigDecimal;import java.util.ArrayList;import java.util.Comparator;import java.util.HashSet;import java.util.List;import java.util.Set;
public class OrderService { public static final int MAX_QUANTITY_PER_LINE = 5;
private final TransactionManager tx; private final CustomerDao customerDao; private final ProductDao productDao; private final OrderDao orderDao;
public OrderService(TransactionManager tx, CustomerDao customerDao, ProductDao productDao, OrderDao orderDao) { this.tx = tx; this.customerDao = customerDao; this.productDao = productDao; this.orderDao = orderDao; }
public PlacedOrder placeOrder(int customerId, int addressId, List<OrderLine> lines) { validate(lines); return tx.inTransaction(() -> { customerDao.findById(customerId).orElseThrow(() -> new CustomerNotFoundException(customerId)); if (!customerDao.hasAddress(customerId, addressId)) { throw new InvalidInputException("Address " + addressId + " is not an address of customer " + customerId); } List<OrderLine> sorted = new ArrayList<>(lines); sorted.sort(Comparator.comparingInt(OrderLine::productId)); // same lock order for every buyer
List<Product> locked = new ArrayList<>(); for (OrderLine line : sorted) { Product p = productDao.findByIdForUpdate(line.productId()) .orElseThrow(() -> new ProductNotFoundException(line.productId())); if (!p.active()) { throw new InvalidInputException(p.name() + " is not for sale"); } if (p.stock() < line.quantity()) { throw new OutOfStockException(p.name(), p.stock(), line.quantity()); } locked.add(p); }
List<OrderItem> items = new ArrayList<>(); for (int i = 0; i < sorted.size(); i++) { Product p = locked.get(i); int quantity = sorted.get(i).quantity(); productDao.updateStock(p.id(), p.stock() - quantity); items.add(new OrderItem(p.id(), quantity, p.price())); } int orderId = orderDao.create(customerId, addressId); orderDao.addItems(orderId, items); return new PlacedOrder(orderId, items.size(), total(items)); }); }
public List<OrderSummary> history(int customerId) { customerDao.findById(customerId).orElseThrow(() -> new CustomerNotFoundException(customerId)); return orderDao.findSummariesByCustomer(customerId); }
private static void validate(List<OrderLine> lines) { if (lines == null || lines.isEmpty()) { throw new InvalidInputException("An order needs at least one product"); } Set<Integer> seen = new HashSet<>(); for (OrderLine line : lines) { if (line.quantity() < 1 || line.quantity() > MAX_QUANTITY_PER_LINE) { throw new InvalidInputException("Quantity must be between 1 and " + MAX_QUANTITY_PER_LINE); } if (!seen.add(line.productId())) { throw new InvalidInputException("Product " + line.productId() + " appears twice"); } } }
private static BigDecimal total(List<OrderItem> items) { BigDecimal total = BigDecimal.ZERO; for (OrderItem item : items) { total = total.add(item.lineTotal()); } return total; }}Placed order #17, total Rs 22397.00 Refused: Only 0 left of Logitech M331 Silent Mouse (you asked for 1) Refused: Address 3 is not an address of customer 1 Refused: No product with id 999 Power bank stock now: 58
What this code does
- The demo calls
placeOrderfour times: 2 power banks and 1 Redmi phone; 1 power bank with the out-of-stock mouse; an address that belongs to another customer; and product 999. Only the first succeeds. - Every check runs before any write, and all of it runs inside one transaction. The second order asked for a power bank too, yet the stock is 58 (60 minus the first order's 2): nothing from a refused order was saved.
- Lines are sorted by product id before locking with
findByIdForUpdate, so two buyers always lock rows in the same order, which prevents deadlocks.
Example 6 · Catching domain and database exceptions in the app layer
import java.sql.SQLException;
class ShopException extends RuntimeException { ShopException(String message) { super(message); }}
class OutOfStockException extends ShopException { OutOfStockException(String product, int available, int requested) { super("Only " + available + " left of " + product + " (you asked for " + requested + ")"); }}
class DataAccessException extends RuntimeException { DataAccessException(String message, Throwable cause) { super(message, cause); }}
public class AppLayerDemo { // The app layer: one place that turns exceptions into what the user sees static void run(String action, Runnable work) { try { work.run(); System.out.println(action + ": done"); } catch (ShopException e) { System.out.println(action + ": Sorry, " + e.getMessage()); } catch (DataAccessException e) { System.out.println(action + ": Something went wrong on our side, please try again"); System.out.println(" [log] " + e.getMessage() + " <- " + e.getCause()); } }
public static void main(String[] args) { run("Order 1", () -> { }); run("Order 2", () -> { throw new OutOfStockException("Logitech M331 Silent Mouse", 0, 1); }); run("Order 3", () -> { throw new DataAccessException("Could not load product 7", new SQLException("Communications link failure", "08S01")); }); }}Order 1: done Order 2: Sorry, Only 0 left of Logitech M331 Silent Mouse (you asked for 1) Order 3: Something went wrong on our side, please try again [log] Could not load product 7 <- java.sql.SQLException: Communications link failure
What this code does
- A broken rule is shown to the user word for word, because
ShopExceptionmessages are written for users. - A database failure gets a calm message for the user and the technical detail, including the
SQLExceptioncause, in the log line. Showing SQL errors to users confuses them and can leak table names.
In ShopLite the domain exceptions all extend ShopException. The app layer catches DataAccessException separately, because a database failure is not the user's fault: the user gets a short "try again" and the full cause belongs in the log.
Next step
Check your understanding
12 quick questions