Video in progress

Strong Junior ⚙️ JVM and memory

Why do these entities cause a StackOverflowError when logged, and how do you fix it?

@Entity @Data
class Author {
    @Id Long id;
    String name;
    @OneToMany(mappedBy = "author") List<Book> books;
}

@Entity @Data
class Book {
    @Id Long id;
    String title;
    @ManyToOne Author author;
}

log.info("Muallif: {}", author);

Author.toString() prints the list of books, and each Book.toString() prints the author again: the bidirectional association turns into endless recursion. You have to exclude one side of the association from toString.

📖 Answer

Lombok's @Data annotation generates toString(), equals() and hashCode() over all the fields. As a result:

Author.toString() -> books.toString() -> Book.toString() -> author.toString() -> books again ...

Every step is a new stack frame, and after a few thousand steps the stack runs out. The same problem exists in hashCode(): adding the entity to a HashSet crashes too. Turning it into JSON with Jackson produces the same cycle.

The fix:

@Entity
@Getter @Setter
@ToString(exclude = "books")
class Author { ... }

@Entity
@Getter @Setter
@ToString(exclude = "author")
class Book { ... }

Extra tips:

  • don't use @Data on JPA entities. Write equals/hashCode yourself, based on the id only;
  • a lazy collection in toString is another risk: if the session is closed you get LazyInitializationException, and if it is open you get unexpected SQL queries;
  • return DTOs from the API, not entities, and then there is no JSON cycle either.