Skip to lesson

The object-relational mismatch

ShopLite's orders and customers are objects in Java but rows in MySQL. Saving and loading them by hand means one SQL string and one mapping loop per table, and the work grows with every column you add.

Recap: hand-written SQL and row mapping

Mapping is copying values between the columns of a database row and the fields of a Java object, in either direction. With JdbcClient you write every mapping yourself, one line per column.

In Section 15, ShopLite's repositories wrote each SQL string by hand. Example 1 shows one: a SELECT, then a mapRow method that turns each row into a record.

Example 1 · The Section 15 style: JdbcClient with hand-written mapping

Runs in: the jpa-lab Spring Boot project with the ShopLite database

Java
// src/main/java/com/shoplite/lab/recap/ProductRow.javapackage com.shoplite.lab.recap;
import java.math.BigDecimal;
record ProductRow(long id, String sku, String name, long categoryId, String categoryName,                  BigDecimal price, int stock, boolean isActive) {}
// src/main/java/com/shoplite/lab/recap/JdbcProductRepository.javapackage com.shoplite.lab.recap;
import java.sql.ResultSet;import java.sql.SQLException;import java.util.Optional;
import org.springframework.jdbc.core.simple.JdbcClient;import org.springframework.stereotype.Repository;
/** The Section 15 style: every SQL string and every column written by hand. */@Repositoryclass JdbcProductRepository {
    private static final String SELECT_PRODUCT = """            SELECT p.product_id, p.sku, p.name, p.category_id, c.name AS category_name,                   p.price, p.stock, p.is_active            FROM products p            JOIN categories c ON c.category_id = p.category_id            """;
    private final JdbcClient jdbc;
    JdbcProductRepository(JdbcClient jdbc) {        this.jdbc = jdbc;    }
    Optional<ProductRow> findById(long id) {        return jdbc.sql(SELECT_PRODUCT + " WHERE p.product_id = :id")                .param("id", id)                .query(JdbcProductRepository::mapRow)                .optional();    }
    private static ProductRow mapRow(ResultSet rs, int rowNum) throws SQLException {        return new ProductRow(                rs.getLong("product_id"),                rs.getString("sku"),                rs.getString("name"),                rs.getLong("category_id"),                rs.getString("category_name"),                rs.getBigDecimal("price"),                rs.getInt("stock"),                rs.getBoolean("is_active"));    }}
// src/main/java/com/shoplite/lab/recap/RecapRunner.java (prints product 6, then a missing one)package com.shoplite.lab.recap;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentclass RecapRunner implements CommandLineRunner {
    private final JdbcProductRepository products;
    RecapRunner(JdbcProductRepository products) {        this.products = products;    }
    @Override    public void run(String... args) {        System.out.println(products.findById(6).orElseThrow());        System.out.println("Product 99: " + products.findById(99));    }}
Sample output
ProductRow[id=6, sku=ACC-AD141, name=boAt Airdopes 141, categoryId=4, categoryName=Accessories, price=1299.00, stock=120, isActive=true]
Product 99: Optional.empty

What this code does

  • The SELECT names every column, and mapRow names them all again to build the record: eight columns, written twice, kept in step by hand.
  • The JOIN fetches category_name in the same query, so the record already has the name. That choice is yours to make, every time.
  • A missing id gives Optional.empty, because .optional() returns an empty Optional when the query finds no row.

This works well and you can see every query. The cost shows as the app grows: every table needs its SELECT, INSERT and UPDATE strings and a mapper that names each column again, so one new column in products means a change to the SQL, the mapper and the record. A typing slip is caught only when the code runs: rs.getString("skuu") compiles, then fails on the first request with SQLException: Column 'skuu' not found.

The examples in this module run in a small lab project, jpa-lab, against the Section 12 ShopLite database; the module project then moves the real shoplite-api over. Lab runs pass --lab.demo=<name>, a lab-only switch that picks which demo runner runs.

Four mismatches between objects and tables

The object-relational mismatch is the gap between Java objects that point to other objects and MySQL rows that are linked only by id numbers. It appears as four differences: references, collections, inheritance and identity.

Objects and tables describe the same data in different shapes. The picture shows the four gaps; the snippet shows the inheritance gap, and Examples 2 and 3 cross the other three by hand.

Java
// Java: a class hierarchyabstract class Payment { int id; BigDecimal amount; }class UpiPayment extends Payment { String upiId; }class CardPayment extends Payment { String cardLast4; }
// MySQL has no "extends". One common layout is a single table:// payments(payment_id, amount, type, upi_id NULL, card_last4 NULL)// A UPI row leaves card_last4 empty; a card row leaves upi_id empty.
Java objects and MySQL tables hold the same data in different shapes. A Java order holds a Customer object, but the orders row holds only the number customer_id. A Java order holds a List of items, but MySQL keeps them as rows in order_items, each with an order_id.

Example 2 · References and collections: turning flat rows into objects by hand

MismatchDemo.javaJava
import java.math.BigDecimal;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
record Customer(int id, String fullName) {}
record OrderItem(String productName, int quantity, BigDecimal unitPrice) {
    BigDecimal lineTotal() {        return unitPrice.multiply(BigDecimal.valueOf(quantity));    }}
record Order(int id, Customer customer, String status, List<OrderItem> items) {
    BigDecimal total() {        BigDecimal total = BigDecimal.ZERO;        for (OrderItem item : items) {            total = total.add(item.lineTotal());        }        return total;    }}
public class MismatchDemo {
    public static void main(String[] args) {        // What a JOIN of orders, customers and order_items returns: one flat row per order item.        // order_id, customer_id, full_name, status, product, quantity, unit_price        String[][] rows = {                {"1", "1", "Asha Rao", "DELIVERED", "Redmi Note 13 5G", "1", "18499.00"},                {"1", "1", "Asha Rao", "DELIVERED", "boAt Airdopes 141", "2", "1299.00"},                {"2", "2", "Ravi Kumar", "DELIVERED", "Clean Code", "1", "499.00"},                {"2", "2", "Ravi Kumar", "DELIVERED", "The Pragmatic Programmer", "1", "650.00"},                {"2", "2", "Ravi Kumar", "DELIVERED", "Atomic Habits", "2", "399.00"},        };
        Map<Integer, Customer> customers = new LinkedHashMap<>();        Map<Integer, List<OrderItem>> itemsByOrder = new LinkedHashMap<>();        Map<Integer, String[]> firstRowOfOrder = new LinkedHashMap<>();        for (String[] row : rows) {            int orderId = Integer.parseInt(row[0]);            int customerId = Integer.parseInt(row[1]);            customers.putIfAbsent(customerId, new Customer(customerId, row[2]));            firstRowOfOrder.putIfAbsent(orderId, row);            itemsByOrder.computeIfAbsent(orderId, id -> new ArrayList<>())                    .add(new OrderItem(row[4], Integer.parseInt(row[5]), new BigDecimal(row[6])));        }        List<Order> orders = new ArrayList<>();        for (Map.Entry<Integer, String[]> e : firstRowOfOrder.entrySet()) {            String[] row = e.getValue();            Customer customer = customers.get(Integer.parseInt(row[1]));            orders.add(new Order(e.getKey(), customer, row[3], itemsByOrder.get(e.getKey())));        }
        System.out.println(rows.length + " rows became " + orders.size() + " Order objects");        for (Order order : orders) {            System.out.println("Order " + order.id() + " for " + order.customer().fullName()                    + ": " + order.items().size() + " items, total Rs " + order.total());        }    }}
Output
5 rows became 2 Order objects
Order 1 for Asha Rao: 2 items, total Rs 21097.00
Order 2 for Ravi Kumar: 3 items, total Rs 1947.00

What this code does

  • A JOIN returns one flat row per order item, so Asha's order appears twice and Ravi's three times. The customer's name repeats on every row.
  • The loop rebuilds the object shape: one Customer object per customer_id (a reference instead of a number) and one List<OrderItem> per order (a collection instead of rows elsewhere).
  • This is about 20 lines for two tables and three fields each. An ORM does this grouping for every entity, from a mapping you write once.

Example 3 · Identity: the same row loaded twice

IdentityDemo.javaJava
import java.util.HashMap;import java.util.Map;
class Category {
    private final int id;    private String name;
    Category(int id, String name) {        this.id = id;        this.name = name;    }
    int getId() {        return id;    }
    String getName() {        return name;    }
    void setName(String name) {        this.name = name;    }}
/** Stands in for the categories table and counts the SELECTs sent to it. */class FakeTable {
    private final Map<Integer, String> rows = Map.of(2, "Mobiles", 3, "Laptops");    int selects = 0;
    String selectName(int id) {        selects++;        return rows.get(id);    }}
/** Like a hand-written repository: every load builds a new object. */class NaiveLoader {
    private final FakeTable table;
    NaiveLoader(FakeTable table) {        this.table = table;    }
    Category load(int id) {        return new Category(id, table.selectName(id));    }}
/** Remembers what it loaded: one object per row (what an ORM does inside a transaction). */class IdentityMapLoader {
    private final FakeTable table;    private final Map<Integer, Category> loaded = new HashMap<>();
    IdentityMapLoader(FakeTable table) {        this.table = table;    }
    Category load(int id) {        return loaded.computeIfAbsent(id, key -> new Category(key, table.selectName(key)));    }}
public class IdentityDemo {
    public static void main(String[] args) {        FakeTable table = new FakeTable();        NaiveLoader naive = new NaiveLoader(table);        Category a = naive.load(2);        Category b = naive.load(2);        a.setName("Smartphones");        System.out.println("Naive:        a == b? " + (a == b) + ", a.equals(b)? " + a.equals(b));        System.out.println("              a says " + a.getName() + ", b says " + b.getName()                + " (SELECTs: " + table.selects + ")");
        FakeTable table2 = new FakeTable();        IdentityMapLoader mapped = new IdentityMapLoader(table2);        Category c = mapped.load(2);        Category d = mapped.load(2);        c.setName("Smartphones");        System.out.println("Identity map: c == d? " + (c == d));        System.out.println("              c says " + c.getName() + ", d says " + d.getName()                + " (SELECTs: " + table2.selects + ")");    }}
Output
Naive:        a == b? false, a.equals(b)? false
              a says Smartphones, b says Mobiles (SELECTs: 2)
Identity map: c == d? true
              c says Smartphones, d says Smartphones (SELECTs: 1)

What this code does

  • The naive loader builds a new object on every load. Row 2 now lives in two objects; renaming one leaves the other with the old name, and neither == nor the default equals sees them as the same category.
  • The identity map remembers each loaded id, so the second load returns the same object and sends no second SELECT.
  • A JPA persistence context is such an identity map: inside one transaction, loading category 2 twice gives you one object. Outside it, the problem comes back (the Persistence context module).

Four differences come up in every project:

  • References vs foreign keys: an Order holds a Customer object; the orders row holds only the number customer_id.
  • Collections vs rows in another table: an Order has a List<OrderItem>; MySQL keeps the items as rows in order_items, each pointing back with order_id.
  • Inheritance vs flat tables: Java can have UpiPayment and CardPayment extend Payment; a table has no extends, so you choose a layout, such as one table with a type column and empty (NULL) columns.
  • Identity: in Java, == asks "same object?" and equals asks "same value?". In a table, the primary key alone decides, so loading the same row twice gives two different objects.

What an ORM does

An ORM (object-relational mapper) is a library that maps classes to tables once, then writes the SQL and turns rows into objects and objects into rows. In Java the standard is JPA, and the most used ORM is Hibernate.

ShopLite's Category class can match the categories table with a few annotations. Example 4 prints the whole table without a single SQL string.

Example 4 · The same table with an ORM: no SQL written

Runs in: the jpa-lab Spring Boot project with the ShopLite database

Category.javaJava
// src/main/java/com/shoplite/lab/category/Category.javapackage com.shoplite.lab.category;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
/** One row of the categories table. */@Entity@Table(name = "categories")public class Category {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "category_id")    private Integer id;
    private String name;
    private Integer parentId;
    protected Category() {        // for Hibernate    }
    public Integer getId() {        return id;    }
    public String getName() {        return name;    }
    public Integer getParentId() {        return parentId;    }}
// src/main/java/com/shoplite/lab/category/CategoryRepository.javapackage com.shoplite.lab.category;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CategoryRepository extends JpaRepository<Category, Integer> {}
System.out.println("Categories in the database: " + categories.count());for (Category c : categories.findAll()) {    System.out.printf("%d %-15s parent=%s%n", c.getId(), c.getName(), c.getParentId());}
Sample output
$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --logging.level.org.hibernate.SQL=DEBUG
    ...
2026-10-16T12:12:33.050+05:30 DEBUG 30040 --- [jpa-lab] [           main] org.hibernate.SQL                        : select count(*) from categories c1_0
Categories in the database: 7
2026-10-16T12:12:33.166+05:30 DEBUG 30040 --- [jpa-lab] [           main] org.hibernate.SQL                        : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0
1 Electronics     parent=null
2 Mobiles         parent=1
3 Laptops         parent=1
4 Accessories     parent=1
5 Books           parent=null
6 Fashion         parent=null
7 Home & Kitchen  parent=null

What this code does

  • @Entity and @Table(name = "categories") map the class to the table; @Column(name = "category_id") maps the id. The field parentId becomes parent_id by Spring Boot's naming rule, so it needs no annotation.
  • CategoryRepository is an empty interface, yet count() and findAll() work: Spring Data JPA writes the class, and Hibernate writes both SELECTs shown in the log.
  • Compare with Example 1: no column list, no mapRow. The SQL still exists; it is just generated, which is why the log is turned on.

An ORM does three jobs. It maps classes to tables (Category to categories, the field parentId to the column parent_id). It writes the SQL for the common cases: load by id, load all, insert, update, delete. And inside a transaction it tracks changed objects: change a field of a loaded object and the ORM sends the UPDATE itself (the Persistence context module shows this).

Inside a transaction the ORM also keeps one object per row, the identity map from Example 3, so == works again for objects loaded in the same unit of work.

What an ORM costs

N+1 queries is a slowdown where one query loads a list of N rows and then N more queries run, one per row, to load something related. A list of 1,000 rows then costs 1,001 queries.

ShopLite prints each category with its parent's name. The code in Example 5 looks harmless; the SQL log shows what it really sends.

Example 5 · The hidden cost: four queries for one small list

Runs in: the jpa-lab Spring Boot project with the ShopLite database

Java
package com.shoplite.lab.costs;
import java.util.List;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
import com.shoplite.lab.category.Category;import com.shoplite.lab.category.CategoryRepository;
/** Looks harmless: print each category with its parent's name. */@Componentclass HiddenQueriesDemo implements CommandLineRunner {
    private final CategoryRepository categories;
    HiddenQueriesDemo(CategoryRepository categories) {        this.categories = categories;    }
    @Override    public void run(String... args) {        List<Category> all = categories.findAll();        for (Category c : all) {            String parent = c.getParentId() == null                    ? "-"                    : categories.findById(c.getParentId()).map(Category::getName).orElse("?");            System.out.println(c.getName() + " (parent: " + parent + ")");        }    }}
Sample output
$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=hidden --logging.level.org.hibernate.SQL=DEBUG
    ...
2026-10-16T11:09:53.268+05:30 DEBUG 2828 --- [jpa-lab] [           main] org.hibernate.SQL                        : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0
Electronics (parent: -)
2026-10-16T11:09:53.386+05:30 DEBUG 2828 --- [jpa-lab] [           main] org.hibernate.SQL                        : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
Mobiles (parent: Electronics)
2026-10-16T11:09:53.399+05:30 DEBUG 2828 --- [jpa-lab] [           main] org.hibernate.SQL                        : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
Laptops (parent: Electronics)
2026-10-16T11:09:53.410+05:30 DEBUG 2828 --- [jpa-lab] [           main] org.hibernate.SQL                        : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
Accessories (parent: Electronics)
Books (parent: -)
Fashion (parent: -)
Home & Kitchen (parent: -)

What this code does

  • findAll() sends the first SELECT. Then each category that has a parent calls findById, one more SELECT each: Mobiles, Laptops and Accessories all load Electronics again.
  • Nothing in the Java code says "query". Only the SQL log shows that 1 + 3 statements went to MySQL; with 1,000 categories it would be about 1,000.
  • Here every repository call runs on its own, so nothing remembers that Electronics was already loaded. Practice 7 does the same work with one query.

An ORM is not free. The SQL is hidden: one innocent-looking method call can send one query or a hundred, and you see nothing unless you turn on SQL logging (the Seeing the SQL lesson). There is also a learning curve: entities, the persistence context, lazy loading and transactions each have rules that surprise beginners.

The classic trap is the N+1 problem from Example 5: each query looks harmless, but together they make a page slow once there are thousands of rows. The Performance traps module fixes it properly. The rule that keeps you safe: always know which SQL your code sends, so turn the SQL log on while you develop and read it.

Predict the output

Count the SQL statements

Each repository call runs on its own. How many statements reach MySQL?

Round 1 of 2

ShopLite has 7 categories, and 3 of them have a parent.

List<Category> all = categories.findAll();
for (Category c : all) {
if (c.getParentId() != null) {
categories.findById(c.getParentId());
}
}

When plain JDBC or JdbcClient is still the better tool

An ORM suits loading, changing and saving objects one at a time: create a customer, change a price, place an order. Example 6 shows work where plain SQL is the better tool.

Example 6 · A report where plain SQL wins: sales by category

Runs in: the jpa-lab Spring Boot project with the ShopLite database

Java
package com.shoplite.lab.report;
import java.math.BigDecimal;import java.util.List;
import org.springframework.jdbc.core.simple.JdbcClient;import org.springframework.stereotype.Repository;
/** A report: one SQL statement does the joining, grouping and adding up inside MySQL. */@Repositoryclass SalesReportRepository {
    record CategorySales(String category, long unitsSold, BigDecimal revenue) {    }
    private final JdbcClient jdbc;
    SalesReportRepository(JdbcClient jdbc) {        this.jdbc = jdbc;    }
    List<CategorySales> salesByCategory() {        return jdbc.sql("""                SELECT c.name AS category,                       SUM(oi.quantity) AS units_sold,                       SUM(oi.quantity * oi.unit_price) AS revenue                FROM order_items oi                JOIN orders o     ON o.order_id = oi.order_id                JOIN products p   ON p.product_id = oi.product_id                JOIN categories c ON c.category_id = p.category_id                WHERE o.status <> 'CANCELLED'                GROUP BY c.name                ORDER BY revenue DESC                """)                .query((rs, n) -> new CategorySales(                        rs.getString("category"), rs.getLong("units_sold"), rs.getBigDecimal("revenue")))                .list();    }}
Sample output
$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --lab.demo=report
    ...
Category        Units      Revenue
Laptops             3    150970.00
Mobiles             4    126397.00
Accessories         9     13941.00
Fashion             6      8594.00
Books              12      5741.00

What this code does

  • One statement joins four tables, skips cancelled orders, groups by category and adds up units and revenue inside MySQL. Java receives only five small rows.
  • Doing this with entities would mean loading every order item as an object and adding them up in Java: more queries, more memory, more code.
  • The repository is still a Spring bean using JdbcClient, and it can live in the same app as JPA repositories. Revenue is BigDecimal, exact to the paisa.

Plain SQL wins when the work is set-based, done on many rows at once inside the database:

  • Reports and dashboards: totals per category or per month are one GROUP BY query; loading every order as an object to add them up in Java is slow and wasteful.
  • Bulk jobs: "raise every Books price by 5%" is one UPDATE statement, not 10,000 loaded objects.
  • Heavy, database-specific SQL: window functions, MySQL-only features, hand-tuned queries.

Real projects use both: Spring Data JPA for the normal create-read-update-delete work, and JdbcClient (or a native query) where plain SQL is clearer and faster. ShopLite will do exactly that.

Next step

Check your understanding

12 quick questions