2022-07-12 23:11:29.209 ERROR 15908 --- [nio-8080-exec-5] 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: 패키지.Member["tickets"]->org.hibernate.collection.internal.PersistentBag[0]->패키지.Ticket["members"]
해당 오류는 양방향 참조를 하는 엔티티들 간의 순환 참조 때문에 발생하는 오류이다.
@JsonBackReference
[@OneToMany에 명시]
양방향 관계에서 역방향(부모->자식) 참조로 어노테이션을 추가하면 직렬화에서 제외된다
entity를 직접적으로 return 해서 발생하는 문제로 DTO를 설정하여 필요한 것만 매핑 하여 문제를 해결 할 수 있다.
Mapping을 편리하게 해주는 라이브러리를 소개하겠다
implementation group: 'org.modelmapper', name: 'modelmapper', version: '3.1.0'
@Configuration을 설정하면 된다.
@Bean
public ModelMapper modelMapper(){
return new ModelMapper();
}
이후 의존성 주입을 하여 사용하면 된다.
//의존성 주입
public final ModelMapper modelMapper;
TicketDTO ticketDTO = modelMapper.map(ticketInfo, TicketDTO.class);