• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

안녕하세요 프로젝션 결과반환을 dto로 하는데 있어 질문을 드립니다

22.01.09 16:00 작성 조회수 430

0

안녕하세요

현재 jpa 모든 강의를 듣고 토이프로젝트를 진행하고 있습니다

질문의 요지는 querydsl을 통해 dto로 조회할때

XXXtoMany 관계의 컬렉션을 함께 조회하고 싶어요

 

현재 제 상황은 이렇습니다

일기장에 일기를 쓰는데

질문을 통해 일기를 쓰는방식이라

일기장에 사용된 질문이 필요해요

 

Diary라는 엔티티가 있고

Question이라는 엔티티가 있는데

이 두 엔티티의 관계가 다대다 관계여서

가운데 DiaryItem이라는 엔티티를 두고

다이어리 페이지에 필요한 모든 정보를

한번에 조회하는것이 목적입니다

 

@QueryProjection 
public DiaryDto(String content, int score, Member member, 
List<DiaryItem> diaryltems) { 
this.content content; 
this 
. score score; 
this. member - 
- new MemberDto(member) ; 
this. diaryltems diaryltems . stream() 
. map (diaryltem new DiaryItemDto(diaryItemj) 
. collect(C011ectors . toList())

 

public MemberDto(Member member) { 
.id = member.getld(); 
this 
this .email = member.getEmaiI(),• 
- member.getusername() 
this. 
username - 
- member.getAvatar(); 
this.avatar -

 

public DiaryItemDto(DiaryItem diaryltem) { 
this . id 
diaryltem . getld(); 
this. question new QuestionDto(diaryItem. getQuestion()) 
this. regDate diaryltem. getRegDate();

 

public QuestionDto(Question question) { 
this. id - question. getld(); 
this .behavior - 
question . getBehavior() ; 
this.type - 
question .getType(); 
this .question = question .getQuestion(); 
this .description question C)

 

 

이런 방식으로 Diary엔티티를 조회할때와 마찬가지로

엔티티에 의존적이지 않게 dto로 받으면서

무한루프에 빠지지 않도록 필요한 정보만 받을 수 있도록

조회를 하는 방법이 궁금해 질문드립니다

 

같은 방식으로 DiaryDto가 아니라 Diary에 담은뒤

Controller에서 DiaryDto의 생성자를 통해 변환을 하면

정상적으로 값이 담겨 오는데

queryFactory의 fetch를 통해

직접 DiaryDto에 담으면 에러가 발생합니다ㅠㅠ

 

현재 이방식으로 쿼리를 실행해보면

query specified join fetching, but the owner of the fetched association was not present in the select list

라는 에러가 나옵니다... 어떤에러인지도 궁금하구요ㅠㅠ

도움부탁드립니다ㅎㅎ

답변 1

답변을 작성해보세요.

1

안녕하세요. 한지훈님

DTO로 조회할 때는 데이터를 flat하게 조회하셔야 합니다. 내부에 컬렉션을 넣을 수 없습니다.

@QueryProjection이 있는 생성자를 보면 diaryItems라는 컬렉션이 있습니다.

활용2편을 통해서 이 부분을 다시 복습하시길 바랍니다.

감사합니다.