Video in progress
What happens when `toString()` or `hashCode()` is called on bidirectionally linked objects (`Order` ↔ `OrderLine`)?
If both classes build toString/hashCode from all their fields, Order calls its lines and each line calls its Order: infinite recursion and a StackOverflowError. You need to leave one side of the link (usually the parent reference) out of these methods.
📖 Answer
class Order {
List<OrderLine> lines = new ArrayList<>();
@Override public String toString() { return "Order" + lines; }
}
class OrderLine {
Order order; String sku;
@Override public String toString() { return "Line(" + sku + ", " + order + ")"; }
}
var o = new Order();
var l = new OrderLine(); l.order = o; l.sku = "A1";
o.lines.add(l);
log.info("saved {}", o); // StackOverflowError
The worst part is that this often shows up when writing logs or when the debugger displays the object, not in the business code. If Lombok @Data or @ToString/@EqualsAndHashCode is on both classes, you get the same result automatically.
hashCode works the same way: when an Order is added to a HashSet, lines.hashCode() → each line's order.hashCode() → ...
Rules:
- on the child side, leave the parent reference out of
toString,equalsandhashCode; if needed, show only the parent's ID; - not putting collections into
toStringat all is also a good habit: an order with 10,000 lines floods the log, and in JPA it triggers lazy loading; - in Jackson the same recursion happens during serialization: use
@JsonManagedReference/@JsonBackReferenceor, better, a DTO.
Ask one more question: does this link really have to be bidirectional? Often OrderLine doesn't need a reference to Order at all.
Sign up to mark studied questions and save your progress.