Error |
s.e.ErrorMvcAutoConfiguration$StaticView : Cannot render error page for request [/api/departments] and exception [Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion
에러 발생 상황 |
Spring JPA구현중
A class에서 @ManyToOne으로 B 맴버 변수 b를 구현 후
B class에서 @OneToMany로 List 맴버 변수 a를 구현했을 때
A나 B 객체를 JSON 포멧으로 변환시 발생
에러 발생 이유 |
1. A객체를 JSON 포멧으로 변환시, b 멤버 변수도 포함
2. b멤버 변수 값은 B객체이고 이 값도 JSON 포멧으로 변환
3. B객체를 JSON으로 포맷할때 a 멤버 변수 값도 포함
4. a 멤버 변수는 List<A> 객체이고 해당 객체도 JSON 포멧으로 변환
5. List<A> 객체가 JSON으로 변환시 해당 객체에 포함된 A객체도 JSON포맷으로 변환
6. 1번 절차 다시 반복
따라서 1~6번 무한 재귀 이므로 Infinite recursion
콘솔창에 아래와 같은 메시지가 남는다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
com.wordata.test.domain.Department["employees"]
->org.hibernate.collection.internal.PersistentBag[0]
->com.wordata.test.domain.Employee["department"]
->com.wordata.test.domain.Department["employees"]
->org.hibernate.collection.internal.PersistentBag[0]
->com.wordata.test.domain.Employee["department"]
->com.wordata.test.domain.Department["employees"]
->org.hibernate.collection.internal.PersistentBag[0]
->com.wordata.test.domain.Employee["department"]
-> 생략...
->com.wordata.test.domain.Department["employees"]
->org.hibernate.collection.internal.PersistentBag[0]
->com.wordata.test.domain.Employee["department"]
->com.wordata.test.domain.Department["employees"]
->org.hibernate.collection.internal.PersistentBag[0]
->com.wordata.test.domain.Employee["department"]
->com.wordata.test.domain.Department["employees"])] as the response has already been committed. As a result, the response may have the wrong status code.
|
cs |
해결 방법 |
해당 에러를 피하기 위해서 B 객체를 JSON으로 변환할때,
a멤버 변수를 포함하지 않게 해야한다.
객체를 JSON으로 변환시 무시해야할 멤버 변수에 @JsonIgnore 어노테이션을 사용할 수 있다.
해당 어노테이션을 a멤버 변수에 붙이면 에러는 발생하지 않는다.