처음 이 에러를 맞닥뜨렸을 때는 "Infinite recursion"라는 메세지만 보고 단순한 순환 참조 에러인 줄 알았다.
그런데 디버깅을 해보니 에러가 발생하는 시점이 데이터를 조회하는 시점이 아니라,
ResponseEntity로 조회한 객체를 리턴할 때, 즉 Entity 객체를 JSON으로 Serialize할 때라는 것을 알게 되었다.
즉, ResponseEntity가 Jackson 라이브러리를 사용하여 객체를 JSON으로 Serialize할 때
순환 참조가 일어나 JSON String이 무한정 늘어나기 때문에 StackOverflowError가 발생하는 것이다.
이에 대한 해결책은 다음 세 개이다.
- JPA Entity 클래스 내에 jackson 애노테이션을 사용하는 방법(@JsonIgnore, @JsonManagedReference, @JsonBackReference, @JsonIdentityInfo, …)
- 별도의 ResponseDTO를 만들어 Entity 객체를 ResponseDTO로 리턴하는 방법
- Custom Serializer를 만들어 사용하는 방법
구체적인 설명과 해결책은 아래 "Green Frog Developer"님이 정말 잘 정리해주셨다.
참고:
imbf.github.io/spring/2020/07/20/Jackson-Infinite-Recursion-Issue-With-JPA-Entity.html
Jackson Infinite Recursion Issue With JPA Entity
이번 포스팅에서는 프로젝트 진행 중 JPA Entity 객체를 JSON으로 Serialize시킬 때 발생하는 Jackson Infinite Recursion Issue에 대해서 알아보고 이를 어떻게 해결했는지에 대해서 포스팅 하도록 하겠다.
imbf.github.io
www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion
Jackson - Bidirectional Relationships | Baeldung
How to use Jackson to break the infinite recursion problem on bidirectional relationships.
www.baeldung.com
'웹 개발 > Spring' 카테고리의 다른 글
[Spring] JPA - How to fix “Error executing DDL ”alter table events drop foreign key {foreign key} “ via JDBC Statement” (0) | 2021.03.12 |
---|---|
[Spring] JPA - @OneToOne 조인 전략을 left join -> inner join 으로 변경하기 (0) | 2021.03.12 |
[Spring] Spring REST Docs 호스트 변경 (0) | 2021.03.04 |
[Spring] @Bean와 @Component의 차이 (0) | 2021.02.24 |
[Spring] 웹 애플리케이션 구조 (0) | 2020.09.10 |