Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] 다대일 양방향 매핑 관계에서 순환 참조 #8

Open
geesuee opened this issue Oct 11, 2021 · 3 comments
Open

[BUG] 다대일 양방향 매핑 관계에서 순환 참조 #8

geesuee opened this issue Oct 11, 2021 · 3 comments
Assignees
Labels
bug Something isn't working

Comments

@geesuee
Copy link
Contributor

geesuee commented Oct 11, 2021

문제 상황

다대일 매핑이 양방향 되어있는 Review-Student / Review-Course 와 같은 관계에서

전체 다(多)에 해당하는 entity 전체 리스트를 반환하는 연산을 수행할 경우(Review 전체를 반환)

  • 해당 entity(Review)는 내부에 매핑된 entity(Student와 Course)를 멤버변수로 갖고 있기 때문에,
    해당 entity 정보를 내부에 담아 반환합니다.
  • 그리고 그렇게 담긴 entity(Student와 Course) 내부에도 양방향으로 매핑된 @onetomany List(reviewList)가 존재하기 때문에 해당 List(reviewList)가 다시 담겨 반환됩니다.

(설명이 좀 이해하기 어려운데 아래 이미지를 보시면 이해에 도움이 될 것 같습니다.)

그러면
전체 후기리스트 안에 > 하나의 후기 안에 > 해당 후기를 작성한 학생 안에 > 그 학생이 작성한 전체 후기리스트 안에 > 하나의 후기리스트 안에 > 해당 후기를 작성한 학생 안에 ...
이런 식으로 무한루프가 진행됩니다..ㅜ
image


해결 방법

- Getter 무한루프에 빠지지 않도록 @onetomany로 매핑된 List에는 @Getter(AccessLevel.NONE)을 선언해주어 더이상 Getter 접근을 할 수 없도록 끊어주어야 합니다.
image
- 해당 처리를 하고 나면, 직접 데이터에 접근(@Getter와 같은 방법으로)할 때에만 매핑된 값을 가져오는 @ManyToOne(fetch=FetchType.LAZY) 조건을 없애주어야 합니다.
그렇지 않으면 매핑된 값을 가져오지 못해 org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor] 에러가 발생합니다.
한마디로 (fetch=FetchType.LAZY)를 삭제해야한다는 것입니다.

  • 🚨 @JsonManagedReference@JsonBackReference 를 사용하여 순환참조는 방지하되, List 객체에 Getter로 접근할 수 있도록 수정
  • 🚨 @ManyToOne 쪽에 @JsonManageReference / @OneToMany 쪽에 @JsonBackReference 사용

해결 후 실행 결과

image


참고 사항

@geesuee geesuee added the bug Something isn't working label Oct 11, 2021
@geesuee geesuee self-assigned this Oct 11, 2021
@geesuee
Copy link
Contributor Author

geesuee commented Oct 11, 2021

@do-oni 앗 제가 템플릿 수정하는 사이에 이전 글에 댓글을 남기셨군요!!
혹시 줄줄이 연관된 모든 entity에 있는
@OneToMany에 Getter 접근 끊어주시고,
(fetch=FetchType.LAZY) 조건도 지워주셨나요??

@do-oni
Copy link
Member

do-oni commented Oct 11, 2021

오,, 아직 모든 entity를 하지는 않았지만 @Getter(**AccessLevel**.NONE) 부분에 빨간줄이 뜨고 뭐라도 생성하라는? 메세지만 나오고 있었는데 계속 하다보니 어느 순간 되었네요 해결책 감사합니다 🤩

@do-oni do-oni pinned this issue Oct 11, 2021
@geesuee geesuee changed the title [BUG] 다대일 양방향 매핑 관계에서 Getter 무한루프 문제 [BUG] 다대일 양방향 매핑 관계에서 순환 참조 Oct 12, 2021
@geesuee
Copy link
Contributor Author

geesuee commented Oct 12, 2021

위 문제는 import 문제였을 것 같네요!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants