Video in progress
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
@Dataon JPA entities. Writeequals/hashCodeyourself, based on theidonly; - a lazy collection in
toStringis another risk: if the session is closed you getLazyInitializationException, 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.
Sign up to mark studied questions and save your progress.