본문 바로가기

개발일지/TIL

[230708] Json 변환시 Entity 순환 참조 문제

에러 

❗ Infinite recursion (StackOverflowError)
    com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError)

 

✔ 에러 테스트 코드

 

@Test
public void entityToJsonTest() throws JsonProcessingException {
    Post post = postRepository.findById(1L).orElseThrow(
            () -> new IllegalArgumentException()
    );

    mapper.writeValueAsString(post);
}

에러 이유

❗ 양방향 연관관계가 있는 Entity가 Json 변환될 때 순환 참조가 일어나고 있었다. 

 

✔ 문제 Entity [Post]

 

@Entity
@Getter
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String writer;
    private String content;
    private LocalDateTime createdAt;

    @ManyToOne
    private User user;
}

 

✔ 문제 Entity [User]

 

@Entity
@Getter
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
    String username;
    String password;

    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
    List<Post> post = new ArrayList<>();
}

해결 방법

✅ Json으로 파싱을 할 때 사용하지 않도록 하는 @JsonIgnore 어노테이션이 있다는 것을 알았다. 이걸 필요한 Entity 멤버 변수에 사용해 해결했다.

 

✔ 수정 Entity [Post]

 

@Entity
@Getter
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String writer;
    private String content;
    private LocalDateTime createdAt;

    @JsonIgnore
    @ManyToOne
    private User user;
}

생각

Entity에 연관관계를 맺을 때 순환 참조를 염두에 두고 작업을 해야 한다는 것을 새삼 느꼈다. 이전에도 @ToString 어노테이션을 사용하면 이러한 문제가 발생할 수 있다는 것을 들었던 적이 있다. 그럼에도 이러한 문제를 부딪혔을 때 바로 떠오르지 않았다. 이번 기회를 통해 Entity 연관관계를 조심히 다루자.