Keeping both sides in sync with helper methods
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A bidirectional link is stored once in the database but twice in Java. When someone changes only one of the two fields, the objects disagree with each other and with MySQL.
addItem and removeItem: one call sets both sides
A helper method is a small method on the parent entity that updates both ends of a link: addItem adds the item to items and sets item.order, and removeItem takes it out and clears item.order.
Callers use the helper instead of touching either field, so the two sides can never disagree.
Example 1 · Order.java and OrderItem.java with helper methods
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
package com.shoplite.lab.order;
import java.math.BigDecimal;import java.time.LocalDateTime;import java.util.ArrayList;import java.util.Collections;import java.util.List;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.EnumType;import jakarta.persistence.Enumerated;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.OneToMany;import jakarta.persistence.OrderBy;import jakarta.persistence.Table;
@Entity@Table(name = "orders")public class Order {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_id") private Integer id;
@Column(name = "customer_id") private Integer customerId;
@Column(name = "address_id") private Integer addressId; // a plain column in this lab
@Enumerated(EnumType.STRING) private OrderStatus status;
@Column(name = "ordered_at") private LocalDateTime orderedAt;
@OneToMany(mappedBy = "order") @OrderBy("id") private List<OrderItem> items = new ArrayList<>();
protected Order() { }
public Order(Integer customerId, Integer addressId, LocalDateTime orderedAt) { this.customerId = customerId; this.addressId = addressId; this.status = OrderStatus.PLACED; this.orderedAt = orderedAt; }
/** Adds the item to this order and points the item at this order: both sides in one call. */ public void addItem(OrderItem item) { items.add(item); item.setOrder(this); }
/** Takes the item out of this order and clears its link: both sides in one call. */ public void removeItem(OrderItem item) { items.remove(item); item.setOrder(null); }
/** Read-only view: callers must use addItem and removeItem. */ public List<OrderItem> getItems() { return Collections.unmodifiableList(items); }
public BigDecimal total() { return items.stream().map(OrderItem::lineTotal).reduce(BigDecimal.ZERO, BigDecimal::add); }
public Integer getId() { return id; } public Integer getCustomerId() { return customerId; } public OrderStatus getStatus() { return status; } public LocalDateTime getOrderedAt() { return orderedAt; }}
package com.shoplite.lab.order;
import java.math.BigDecimal;
import com.shoplite.lab.product.Product;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.FetchType;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.JoinColumn;import jakarta.persistence.ManyToOne;import jakarta.persistence.Table;
@Entity@Table(name = "order_items")public class OrderItem {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_item_id") private Integer id;
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "order_id") private Order order; // the owning side: holds order_id
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "product_id") private Product product;
private int quantity;
@Column(name = "unit_price") private BigDecimal unitPrice;
protected OrderItem() { }
public OrderItem(Product product, int quantity, BigDecimal unitPrice) { this.product = product; this.quantity = quantity; this.unitPrice = unitPrice; }
void setOrder(Order order) { // package-private: only Order calls it this.order = order; }
public BigDecimal lineTotal() { return unitPrice.multiply(BigDecimal.valueOf(quantity)); }
public Integer getId() { return id; } public Order getOrder() { return order; } public Product getProduct() { return product; } public int getQuantity() { return quantity; } public BigDecimal getUnitPrice() { return unitPrice; }}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 Before: 2 items, total 19298.00 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 (?,?,?,?) After: 3 items, total 19797.00 DEBUG SQL - select count(oi1_0.order_item_id) from order_items oi1_0 where oi1_0.order_id=? Rows in order_items for order 14: 3
What this code does
addItemadds toitemsand callsitem.setOrder(this);setOrderhas nopublic, so only classes incom.shoplite.lab.ordercan call it.total()adds uplineTotal()of the items in memory: 17999.00 + 1299.00 + 499.00 = 19797.00, and it matches the 3 rows in MySQL.- Order 14 has a customer and an address; in this lab they are plain
Integercolumns so the example stays about items. The ShopLite project maps them as links.
The previous lesson showed that Hibernate writes only the owning side, and people forget one of the two lines. Each mistake has a different symptom: a NULL foreign key, or a list that is wrong in memory. One method makes the right thing the only easy thing.
Make the child's setter package-private (void setOrder(Order order), no public) and keep both classes in the same feature package. Then only Order can call it, and nothing outside the package can set one side alone.
Trace the code
Both sides, one after the other
A helper has to change both fields. Step through adding and removing a phone.
Variables
- items
- []
- orderOfPhone
- none
Output
(nothing printed yet)Line 6The order's list of items starts empty.
An unmodifiable getter
An unmodifiable view is a read-only wrapper over a list, made with Collections.unmodifiableList(items). Reading works; add, remove and clear throw UnsupportedOperationException. It is a view, not a copy, so it always shows the current items.
If getItems() returns the real list, order.getItems().add(item) skips the helper. Return a read-only view instead.
Example 2 · OrderLabService.tryToBypassHelpers(): the read-only view
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/order/OrderLabService.java (one method)@Transactionalpublic void tryToBypassHelpers() { Order order = orders.findById(14).orElseThrow(); try { order.getItems().add(new OrderItem(products.getReferenceById(9), 1, new BigDecimal("499.00"))); } catch (UnsupportedOperationException e) { System.out.println("Caught " + e.getClass().getName()); }}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=? Caught java.lang.UnsupportedOperationException
What this code does
getItems()returnsCollections.unmodifiableList(items), soaddthrows before anything changes.- The items
SELECTnever ran: the view wraps the lazy list without loading it, and the call failed before it needed the rows. - The only way to add an item is now
order.addItem(item), which also sets the owning side.
The view copies nothing, and Hibernate still works with the real items field inside the entity, so lazy loading and change tracking are untouched.
The exception appears the first time someone tries to bypass the rules, usually in a test, which is exactly when you want to find out.
Stale data in one transaction when helpers are missing
Stale data is a Java object that no longer matches its database row. Inside one transaction Hibernate keeps one object per row and does not reload it, so a list changed on one side only keeps showing the old content.
Set only item.setOrder(order) and save: the row exists in MySQL, but the order already loaded still shows its old list. Compare both runs.
Example 3 · AddItemService.java: owning side only vs the helper
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
package com.shoplite.lab.order;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.product.Product;import com.shoplite.lab.product.ProductRepository;
@Serviceclass AddItemService {
private final OrderRepository orders; private final OrderItemRepository orderItems; private final ProductRepository products;
AddItemService(OrderRepository orders, OrderItemRepository orderItems, ProductRepository products) { this.orders = orders; this.orderItems = orderItems; this.products = products; }
@Transactional public void addBook(boolean useHelper) { Order order = orders.findById(14).orElseThrow(); System.out.println("Before: " + order.getItems().size() + " items, total " + order.total());
Product cleanCode = products.findById(9).orElseThrow(); OrderItem item = new OrderItem(cleanCode, 1, cleanCode.getPrice()); if (useHelper) { order.addItem(item); // sets both sides } else { item.setOrder(order); // owning side only } orderItems.save(item);
System.out.println("After: " + order.getItems().size() + " items, total " + order.total()); System.out.println("Rows in order_items for order 14: " + orderItems.countByOrderId(14)); }}
package com.shoplite.lab.order;
import org.springframework.data.jpa.repository.JpaRepository;
public interface OrderItemRepository extends JpaRepository<OrderItem, Integer> {
long countByOrderId(Integer orderId);}--- addBook(false): item.setOrder(order) only 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 Before: 2 items, total 19298.00 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 (?,?,?,?) After: 2 items, total 19298.00 DEBUG SQL - select count(oi1_0.order_item_id) from order_items oi1_0 where oi1_0.order_id=? Rows in order_items for order 14: 3 --- addBook(true): order.addItem(item) 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 Before: 2 items, total 19298.00 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 (?,?,?,?) After: 3 items, total 19797.00 DEBUG SQL - select count(oi1_0.order_item_id) from order_items oi1_0 where oi1_0.order_id=? Rows in order_items for order 14: 3
What this code does
- Both runs send the same INSERT, and MySQL has 3 rows for order 14 both times. The database was never the problem.
- Without the helper, the loaded
orderstill says 2 items and 19298.00 after the save: stale data that the rest of this transaction would use. - With the helper, memory and database agree: 3 items, total 19797.00. The count query proves the row really exists.
Stale data causes real bugs: an invoice email with the old total, a stock check that misses the new line, a response that does not show what was just added. Nothing fails; the numbers are simply wrong.
With order.addItem(item) the list and the row agree immediately: 3 items and the new total, with exactly the same SQL.
StackOverflowError and JSON recursion: never serialize entities
StackOverflowError is the error Java throws when method calls nest so deeply that the thread's stack is full. Two linked entities whose toString() methods print each other call themselves back and forth until it happens.
Linked entities point at each other, so any code that follows every link never ends.
Example 4 · toString() on both sides: StackOverflowError
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
// Order.java (variant)@Overridepublic String toString() { return "Order{id=" + id + ", status=" + status + ", items=" + items + "}";}
// OrderItem.java (variant)@Overridepublic String toString() { return "OrderItem{id=" + id + ", quantity=" + quantity + ", order=" + order + "}";}
// OrderLabService.java@Transactional(readOnly = true)public void printOrder() { System.out.println(orders.findById(14).orElseThrow());}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 ERROR SpringApplication - Application run failed java.lang.StackOverflowError at java.base/java.lang.String.valueOf(String.java:4465) at com.shoplite.lab.order.OrderItem.toString(OrderItem.java:58) at java.base/java.lang.String.valueOf(String.java:4465) at java.base/java.lang.StringBuilder.append(StringBuilder.java:173) at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:459) at org.hibernate.collection.spi.PersistentBag.toString(PersistentBag.java:638) at java.base/java.lang.String.valueOf(String.java:4465) at com.shoplite.lab.order.Order.toString(Order.java:78) ...
What this code does
- Printing the order prints its items; each item prints its order, which prints its items again. The stack trace shows
Order.toStringandOrderItem.toStringrepeating. - The items
SELECTran becausetoStringtouched the lazy list; a carelesstoStringalso loads data. - The fix:
"OrderItem{id=" + id + ", quantity=" + quantity + "}"with no linked entity, and the same forOrder.
Example 5 · Jackson on an entity vs on a response record
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/order/OrderLabService.java (two methods)@Transactional(readOnly = true)public String entityAsJson() { return jsonMapper.writeValueAsString(orders.findById(14).orElseThrow());}
@Transactional(readOnly = true)public String viewAsJson() { return jsonMapper.writeValueAsString(OrderView.from(orders.findById(14).orElseThrow()));}
// src/main/java/com/shoplite/lab/order/OrderView.javapackage com.shoplite.lab.order;
import java.math.BigDecimal;import java.util.List;
/** What the outside world sees: plain data, no links back. */record OrderView(Integer id, String status, List<ItemView> items, BigDecimal total) {
record ItemView(String sku, int quantity, BigDecimal lineTotal) { }
static OrderView from(Order order) { List<ItemView> items = order.getItems().stream() .map(i -> new ItemView(i.getProduct().getSku(), i.getQuantity(), i.lineTotal())) .toList(); return new OrderView(order.getId(), order.getStatus().name(), items, order.total()); }}--- entityAsJson()
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 - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG SQL - select c1_0.parent_id,c1_0.category_id,c1_0.name from categories c1_0 where c1_0.parent_id=? order by c1_0.category_id
ERROR SpringApplication - Application run failed
tools.jackson.core.exc.StreamConstraintsException: Document nesting depth (501) exceeds the maximum allowed (500, from `StreamWriteConstraints.getMaxNestingDepth()`) (through reference chain: com.shoplite.lab.order.Order["items"]->java.util.Collections$UnmodifiableList[0]->com.shoplite.lab.order.OrderItem["product"]->com.shoplite.lab.product.Product$HibernateProxy["category"]->com.shoplite.lab.category.Category$HibernateProxy["parent"]->com.shoplite.lab.category.Category$HibernateProxy["children"]->org.hibernate.collection.spi.PersistentBag[0]->com.shoplite.lab.category.Category$HibernateProxy["parent"]->com.shoplite.lab.category.Category$HibernateProxy["children"]->...
--- viewAsJson()
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 - 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=?
{"id":14,"status":"SHIPPED","items":[{"sku":"MOB-RN13","quantity":1,"lineTotal":17999.00},{"sku":"ACC-AD141","quantity":1,"lineTotal":1299.00}],"total":19298.00}What this code does
jsonMapperis thetools.jackson.databind.json.JsonMapperbean Spring MVC uses for responses, so this is what a controller returning the entity would do.- For the entity, Jackson follows order, items, product, category, parent and children until the nesting limit, loading categories on the way. The chain in the message shows the loop.
OrderViewis a record with only the fields the client needs, built inside the transaction: 4 SELECTs, clean JSON, no links back.
Write toString() with plain fields and ids only, never with linked entities or collections. Jackson, the JSON library Spring uses, loops the same way when a controller returns an entity: it follows every getter (order, items, product, category, parent, children) and back. Jackson 3 (in Spring Boot 4) stops at 500 nested levels with "Document nesting depth (501) exceeds the maximum allowed"; older versions overflowed the stack. On the way it also fires a lazy load for every link it touches.
The fix is a design rule, not an annotation: entities never leave the service. The service maps them to a response record (a DTO) inside the transaction, with exactly the fields the API contract lists and no links back. @JsonIgnore or @JsonManagedReference can stop the loop, but they tie the API format to the entity and still load data nobody asked for.
Next step
Check your understanding
12 quick questions