관리 메뉴

JAN's History

[Spring] @JsonIgnoreProperties()로 무한참조 버그 잡기 본문

Error zip

[Spring] @JsonIgnoreProperties()로 무한참조 버그 잡기

JANNNNNN 2024. 5. 13. 21:00

에러

WARN 25144 --- [nio-8080-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.SignServer.Dto.CommentDto]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': no back reference property found from type java.util.Set<com.example.SignServer.Entity.Comment>
WARN 25144 --- [nio-8080-exec-1] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.SignServer.Dto.CommentDto]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': no back reference property found from type java.util.Set<com.example.SignServer.Entity.Comment>
WARN 25144 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported]

상황

좋아요 기능을 구현하던 도중 jackson에러가 발생...

like를 하지 않으면 에러가 발생하지 않지만, like를 하면 에러가 발생하는 상황

해결책

무한참조가 원인이었다!

오류에 대해서 찾아보니 Jackson이 JSON을 엔티티 객체로 역직렬화할 때 순환 참조(circular reference) 혹은 양방향 참조(bidirectional reference)를 처리하지 못하여 발생하는 문제와 주로 JSON 직렬화 과정에서 발생하는 오류로 같은 ID를 가진 객체가 두 번 이상 참조되어 발생하는 것이라고 한다.

Postman
Postman

즉, 나의 경우에는 user->image->likes->images->likes-> images ->like-> images ->like ...가 무한참조 되고 있던 것!

@JsonIgnoreProperties 

public class Image{
...
    @JsonIgnoreProperties({"image"}) //무한참조 방지
        @OneToMany(mappedBy = "image")
        private List<Likes> likes;
}

Image에서 likes 무한참조를 막아줍니다.

public class Likes {

    @JsonIgnoreProperties({"images"}) // 적용
    @JoinColumn(name = "userId")
    @ManyToOne(fetch = FetchType.LAZY)
    private User user;


}

또한 Likes에서도 user와 양방향 연관관계가 맺어져있기 때문에 Likes를 통해 User 정보를 조회할 때 User images 필드는 JSON 직렬화에서 제외되어 무한 참조 문제가 해결됩니다!

해결완료🫠