카테고리 없음
[Error] java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
Code Canvas
2025. 4. 10. 13:33
1. 순환 참조(Circular Reference) 에러 발생
- 순환 참조는 객체 A가 객체 B를 참조하고, B가 다시 A를 참조하는 형태를 말한다. 아래의 관계를 그대로 Controller에서 JSON으로 변환하여 응답하면 [Error] java.lang.IllegalStateException: Cannot call sendError() after the response has been committed 에러가 발생한다. 이것을 JPA 순환참조 오류라고 한다.
class Parent {
@OneToMany(mappedBy="child")
List<Child> children;
}
class Child {
@ManyToOne
Parent parent;
}
2. 순환 참조 문제
Parent p = new Parent();
Child c = new Child();
p.children = List.of(c);
c.parent = p;
objectMapper.writeValueAsString(p);
Parent → children → Child로 들어감
Child → parent → 다시 Parent로 돌아감
그리고 또 다시 그 Parent의 children을 탐색하고... 무한 반복!
→ 결국 스택 오버플로우(StackOverflowError) 혹은
Jackson이 "순환 참조 발견!" 하고 HttpMessageNotWritableException 예외를 던짐
3. 해결: @JsonManagedReference, @JsonBackReference
- @JsonManagedReference: JSON으로 출력할 "정방향 관계" → children 리스트는 JSON에 포함됨
- @JsonBackReference: JSON으로 출력하지 않을 "역방향 관계" → Child.parent는 JSON에 포함되지 않음
class Parent {
@OneToMany(mappedBy="child")
@JsonManagedReference
List<Child> children;
}
class Child {
@ManyToOne
@JsonBackReference
Parent parent;
}