강의

멘토링

로드맵

인프런 커뮤니티 질문&답변

이승은님의 프로필 이미지
이승은

작성한 질문수

스프링부트-JPA-API개발-성능최적화 강의를 듣는데 Hibernate5Module를 주석 해제하면 오류가 나요

작성

·

218

0

@SpringBootApplication
public class JpashopApplication {

	public static void main(String[] args) {
		SpringApplication.run(JpashopApplication.class, args);
	}

	@Bean
	Hibernate5Module hibernate5Module() {
		Hibernate5Module hibernate5Module = new Hibernate5Module();
		//강제 지연 로딩 설정
//		hibernate5Module.configure(Hibernate5Module.Feature.FORCE_LAZY_LOADING, true);
		return hibernate5Module;
	}
}


강의에서 저 부분을 주석처리해서 포스트맨에서 확인하는데 저는 저걸 주석 처리만 하면 에러가 나요

그래서 주석 안해놓고 돌리는데, 에러 메시지를 보면 무한루프 도는 것 같거든요?

@JsonIgnore 설정때문인건지 일단 에러 발생하는 것들은 아래 2개입니다.

 

java.lang.StackOverflowError: null

java.lang.IllegalStateException: Cannot call sendError() after the response has been committed

 

2023-11-28 10:46:23.857 ERROR 23972 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: jpabook.jpashop.domain.OrderItem["order"]->jpabook.jpashop.domain.Order["orderItems"]->org.hibernate.collection.internal.PersistentBag[0]->jpabook.jpashop.domain.OrderItem["order"]->jpabook.jpashop.domain.Order["orderItems"]->org.hibernate.collection.internal.PersistentBag[0]->jpabook.jpashop.domain.OrderItem["order"]->jpabook.jpashop.domain.Order["orderItems"]->org.hibernate.collection.internal.PersistentBag[0]->jpabook.jpashop.domain.OrderItem["order"]->jpabook.jpashop.domain.Order["orderItems"]->org.hibernate.collection.internal.PersistentBag[0]->

답변 1

0

안녕하세요, 인프런 AI 인턴입니다.

이승은님, Hibernate5Module 설정과 관련하여 문제를 겪고 계신 것 같습니다. 여기서 지적하신 무한 루프 문제는 엔티티 간의 양방향 참조가 JSON으로 변환될 때 상호 참조로 인해 발생하는 재귀 호출 때문입니다.

에러 메시지에 나타난 StackOverflowError는 한 객체가 자기 자신을 지속적으로 참조하며 직렬화하려고 할 때 발생합니다. @JsonIgnore의 사용은 특정 엔티티의 직렬화 과정에서 이 필드를 무시하여 처리하고자 할 때 사용하는 것으로, 이 상황에서는 양방향 참조를 끊어주는 역할을 할 수 있습니다.

Hibernate5ModuleFORCE_LAZY_LOADING 설정의 경우, 이는 지연 로딩된 프로퍼티들을 강제로 로딩하게 하여 엔티티를 JSON으로 변환하려고 할 때 초기화하지 않은 프록시를 강제로 로딩하게 할 수 있습니다. 이 설정이 주석되어 있다면, 지연 로딩된 객체들이 실제로 필요할 때까지 로딩되지 않게 됩니다.

따라서 이 문제를 해결하기 위해 몇 가지 방법을 시도해볼 수 있습니다:

  1. @JsonIgnore를 양방향 참조 중 한쪽에 추가하여 무한 루프를 방지합니다.
  2. @JsonManagedReference@JsonBackReference를 사용하여 부모-자식 관계를 명시합니다.
  3. DTO(Data Transfer Object)를 사용하여 엔티티를 직접 노출하지 않고 데이터를 필요한 부분만 전송하는 방법으로 처리합니다.

문제가 발생하는 부분과 관련하여 양방향 참조가 존재하는 엔티티의 관계를 점검하시고, 위 방법 중 적절한 방법을 선택하여 적용해보시길 권장드립니다.

이승은님의 프로필 이미지
이승은

작성한 질문수

질문하기