Skip to lesson

Practice: relationships

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

A pull request adds a new link to ShopLite, and the review asks three things: which table holds the foreign key, who owns the child's life, and what SQL it sends.

Mapping a schema's foreign keys to relationships

Each foreign key in a schema becomes one relationship. Read the schema one key at a time.

Example 1 · ShopLite's Order and OrderItem mappings, and the SQL of one save

Runs in: the shoplite-api Spring Boot project

Java
@ManyToOne(fetch = FetchType.LAZY, optional = false)@JoinColumn(name = "customer_id", nullable = false)private Customer customer;
@ManyToOne(fetch = FetchType.LAZY, optional = false)@JoinColumn(name = "address_id", nullable = false)private Address deliveryAddress;
/** Items belong to their order: saved, merged and deleted with it. */@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)@OrderBy("id")private List<OrderItem> items = new ArrayList<>();
@Testvoid oneSaveStoresTheOrderAndItsItems() {    Customer asha = customers.getReferenceById(1);    Address home = addresses.getReferenceById(1);    Product book = products.findById(9).orElseThrow();    Product earbuds = products.findById(6).orElseThrow();
    Order order = new Order(asha, home, LocalDateTime.of(2026, 10, 16, 11, 42));    order.addItem(new OrderItem(book, 1, book.getPrice()));    order.addItem(new OrderItem(earbuds, 2, earbuds.getPrice()));    orders.save(order);                               // cascade PERSIST saves both items    em.flush();    em.clear();                                       // forget everything: next read comes from MySQL
    OrderResponse read = orderService.get(order.getId());    assertThat(read.items()).extracting(OrderItemResponse::sku).containsExactly("BK-CLEAN", "ACC-AD141");    assertThat(read.total()).isEqualByComparingTo(new BigDecimal("3097.00"));}
Output (mvn test, SQL lines of the first test)
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : insert into orders (customer_id,address_id,ordered_at,status) values (?,?,?,?)
DEBUG org.hibernate.SQL : insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?)
DEBUG org.hibernate.SQL : insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?)
DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=?
DEBUG org.hibernate.SQL : select i1_0.order_id,i1_0.order_item_id,i1_0.product_id,i1_0.quantity,i1_0.unit_price from order_items i1_0 where i1_0.order_id=? order by i1_0.order_item_id
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?

What this code does

  • Three foreign keys of orders and order_items become three lazy @ManyToOnes; getReferenceById gives the customer and address as proxies, so no SELECT for them.
  • One save sends the order INSERT, then one INSERT per item with the new order id: exactly the prediction rule above.
  • After em.clear() the read is real: order, its items, then one SELECT per product as OrderItemResponse.from touches each lazy product.

Each FOREIGN KEY (x_id) REFERENCES parents becomes a lazy @ManyToOne with @JoinColumn(name = "x_id") on the entity of that table. Add UNIQUE on the column and it is a @OneToOne; make it the primary key and it is a @OneToOne with @MapsId. Then decide, per link, whether the parent needs a collection: yes for small lists you work with through the parent (Order.items, Customer.addresses), no for lists that grow without limit (Category.products, Customer.orders). A table whose only job is to connect two others is a many-to-many: @ManyToMany if it has just the two ids, a join entity if it has data.

ShopLite has seven foreign-key links: addresses.customer_id, categories.parent_id, products.category_id, orders.customer_id, orders.address_id, order_items.order_id and order_items.product_id.

Fixing missing mappedBy, wrong owners and wrong cascades

Most relationship bugs fall into four groups, and each has a recognisable error. Read the message first: it names the entity, the field or the column.

Example 2 · Mistake: the owning side was never set

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// Bug: only the inverse list is changedwatches.getProducts().add(watch);products.save(watch);
// Fix: set the owning side (the field with @JoinColumn)watch.setCategory(watches);products.save(watch);
Output (relations lab, each run on a fresh database)
--- Bug
DEBUG SQL - insert into categories (name,parent_id) values (?,?)
TRACE bind - binding parameter (1:VARCHAR) <- [Smart Watches]
TRACE bind - binding parameter (2:INTEGER) <- [1]
DEBUG SQL - insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?)
TRACE bind - binding parameter (1:BOOLEAN) <- [true]
TRACE bind - binding parameter (2:INTEGER) <- [null]
TRACE bind - binding parameter (3:VARCHAR) <- [Noise ColorFit Pro 5]
TRACE bind - binding parameter (4:NUMERIC) <- [3499.00]
TRACE bind - binding parameter (5:VARCHAR) <- [ACC-SW01]
TRACE bind - binding parameter (6:INTEGER) <- [25]
WARN  error - HHH000247: ErrorCode: 1048, SQLState: 23000
WARN  error - Column 'category_id' cannot be null
DataIntegrityViolationException: Column 'category_id' cannot be null
--- Fix
DEBUG SQL - insert into categories (name,parent_id) values (?,?)
TRACE bind - binding parameter (1:VARCHAR) <- [Smart Watches]
TRACE bind - binding parameter (2:INTEGER) <- [1]
DEBUG SQL - insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?)
TRACE bind - binding parameter (1:BOOLEAN) <- [true]
TRACE bind - binding parameter (2:INTEGER) <- [8]
TRACE bind - binding parameter (3:VARCHAR) <- [Noise ColorFit Pro 5]
TRACE bind - binding parameter (4:NUMERIC) <- [3499.00]
TRACE bind - binding parameter (5:VARCHAR) <- [ACC-SW01]
TRACE bind - binding parameter (6:INTEGER) <- [25]
Saved product 16 in category 8
watches.getProducts().size() = 0

What this code does

  • In the bug, parameter 2 (category_id) is bound to [null]: Hibernate ignored the mappedBy list.
  • In the fix it is bound to [8], the new category's id, and the INSERT succeeds.
  • The last line of the fix is still 0: only a helper method that sets both sides keeps the list right too.

Missing mappedBy on a collection: "Schema validation: missing table [orders_items]" at startup, or an extra UPDATE per child. Wrong mappedBy value: "...is 'mappedBy' a property named 'x' which does not exist in the target entity". Owning side not set: "Column 'order_id' cannot be null", or a silent NULL on a nullable column.

Wrong cascades show up as missing rows (no cascade on an owned collection: the children are never saved), "references an unsaved transient instance" (a link to a new object without cascade), or deletes that go too far ("Cannot delete or update a parent row" from REMOVE on a shared entity). Fix the mapping, not the symptom; adding cascade = ALL to silence a transient error is the classic wrong fix.

Predicting the SQL for a parent with children

To predict what a save sends, walk the objects in the order Hibernate does. Count the statements before you run the code, then compare with the log.

Example 3 · Predicting the SQL: swapping an item in an existing order

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// CascadeLabService.java (relations lab); Order.items has cascade = ALL, orphanRemoval = true@Transactionalpublic void swapItem() {    Order order = orders.findById(15).orElseThrow();      // one item: the Lenovo laptop    OrderItem old = order.getItems().get(0);    order.removeItem(old);    Product book = products.findById(11).orElseThrow();    order.addItem(new OrderItem(book, 1, book.getPrice()));}
Output (fresh database)
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=?
DEBUG SQL - select i1_0.order_id,i1_0.order_item_id,i1_0.product_id,i1_0.quantity,i1_0.unit_price from order_items i1_0 where i1_0.order_id=? order by i1_0.order_item_id
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG SQL - insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?)
DEBUG SQL - delete from order_items where order_item_id=?

What this code does

  • Three SELECTs: the order, its items (first use of the list), and the book.
  • At commit Hibernate inserts the new item (cascade PERSIST) and then deletes the orphan (orphanRemoval): inserts before deletes.
  • No UPDATE on orders: no field of the order itself changed.

New parent with cascade = ALL on its children: INSERT the parent (it needs an id first), then one INSERT per child with the parent's id. Existing parent: nothing for the parent unless a field changed; one INSERT per new child, one DELETE per orphan. At flush, inserts run before orphan deletes.

Reads follow the fetch rules: one SELECT for the parent, one for a lazy collection when first used, and one per lazy @ManyToOne you touch that is not loaded yet (the same row loads only once per transaction). A count higher than expected is the first sign of an EAGER link, a missing mappedBy or an N+1 loop.

Interview drill: owning side, join entity, cascade vs orphanRemoval

Three relationship questions come up in almost every JPA interview. Answer each in two or three sentences with one ShopLite example.

The three answers in short:

  • Owning side: the field whose table has the foreign key, the side without mappedBy; Hibernate writes the column only from it.
  • Join entity vs @ManyToMany: @ManyToMany maps a link table with only two ids; as soon as the link has data (quantity, unit price, a date) it becomes an entity with two @ManyToOnes, like OrderItem.
  • Cascade vs orphanRemoval: cascade passes operations from parent to children (save the order, its items are saved); orphanRemoval deletes a child that leaves the collection while the parent stays.

Expect a follow-up on each: "why LAZY?", "why Set for many-to-many?", "why not cascade on Product.category?". The Interview tab has model answers.

Finish up

Mark complete & continue

Next: ShopLite: connect the entities