Hibernate: Bidirectional toString causes a StackOverflowError

Parent prints child, child prints parent. Lombok's @Data generates exactly this by default.

Code
@Entity
@Data                      // includes toString of ALL fields
class Order {
    @OneToMany(mappedBy = "order") List<OrderItem> items;
}

@Entity
@Data
class OrderItem {
    @ManyToOne Order order;    // back to the start
}
Output
java.lang.StackOverflowError
  at Order.toString -> OrderItem.toString -> Order.toString ...

Fix: @ToString(exclude = "order") or write toString by hand.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11