escape-room

[QueryDSL] org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list 에러

기매_ 2023. 5. 25. 01:11

문제 상황

@Override
public ThemeDetailDTO themeDetail(Long themeId) {

    return queryFactory
            .select(new QThemeDetailDTO(
                    theme.id,
                    theme.name,
                    theme.genre,
                    theme.activity,
                    theme.difficult,
                    theme.limitTime,
                    theme.recommendStart,
                    theme.recommendEnd,
                    theme.info,
                    theme.imageUrl,
                    cafe.id,
                    cafe.name,
                    cafe.domain,
                    cafe.location,
                    Expressions.template(Double.class, "ROUND({0}, 2)", review.rating.avg().coalesce(-1.0))
            ))
            .from(theme)
            .leftJoin(theme.cafe, cafe)
            .leftJoin(theme.reviews, review)
            .where(theme.id.eq(themeId))
            .fetchOne();
}

 

처음에 위와 같이 코드를 작성하였는데, 문득 fetch join 이 추가되면 SQL문이 어떻게 출력될지 궁금해졌다.

 

따라서 .fetchJoin() 을 추가하여 아래와 같이 코드를 작성해봤다 

@Override
public ThemeDetailDTO themeDetail(Long themeId) {

    return queryFactory
            .select(new QThemeDetailDTO(
                    theme.id,
                    theme.name,
                    theme.genre,
                    theme.activity,
                    theme.difficult,
                    theme.limitTime,
                    theme.recommendStart,
                    theme.recommendEnd,
                    theme.info,
                    theme.imageUrl,
                    cafe.id,
                    cafe.name,
                    cafe.domain,
                    cafe.location,
                    Expressions.template(Double.class, "ROUND({0}, 2)", review.rating.avg().coalesce(-1.0))
            ))
            .from(theme)
            .leftJoin(theme.cafe, cafe).fetchJoin()
            .leftJoin(theme.reviews, review)
            .where(theme.id.eq(themeId))
            .fetchOne();
}

 

그리고 실행하였더니 런타임 시 아래와 같은 오류가 발생하였다.

org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list


원인

fetch join을 사용하는 이유는 엔티티 상태에서 엔티티 그래프를 참조하기 위해서 사용하는 것이다.

따라서 당연히 엔티티가 아닌 DTO 상태로 조회하는 것은 불가능하다.
DTO로 조회할 경우 fetch join을 사용하면 안되며, 그냥 순수한 join을 사용해야 한다 .. !

 

=> 즉, DTO 형식의 반환형에 fetchJoin()을 사용하면 안된다.


즉 DTO로 조회하는 경우에는 내가 처음에 했었던대로 순수한 join을 사용해서 데이터를 조회해야 한다.

 

혹시 DTO로 조회한 것이 아닌데 이 오류가 발생하였다면 아래 글을 참고해보자.

https://www.inflearn.com/questions/240949/fetchjoin-%EC%97%90%EB%9F%AC-%EB%B0%9C%EC%83%9D

 

fetchJoin() 에러 발생 - 인프런 | 질문 & 답변

안녕하세요fetchJoin() 할 때 에러가 발생하는데 해결방법을 찾을 수 없어 조언을 구합니다정상 동작query.from(A).leftjoin(A.B , B).fetchJoin()에러 발생query.from(A).leftjoin(A.B , B).fetchJoin().le...

www.inflearn.com