본문 바로가기

SQL

JPQLQUery에서의 Fetch Join

left (outer) join

  • 첫번째(left) 테이블에 연관 관계가 있는 모든 데이터 가져오기. 연관 데이터가 없으면 null로 채워서라도...
  • 첫번째 테이블 컬럼만 본다면 중복 row 발생

fetchJoin

  • join 관계의 데이터도 같이 가져온다.

LEFT 가 Study고, right가 QTag table일때,

 

따라서 Left Join된 테이블의 모든 데이터인 Study table의 데이터와 더불어 Fetch join을 통해 QTag와 관련된 정보들도 같이 가져올 수 있도록 함.

 

자세한건 아래 코드 두개를 비교해보자

두번째 사진의 SQL문:

 select
        distinct study0_.id as id1_7_0_,
        tag2_.id as id1_12_1_,
        study0_.closed as closed2_7_0_,
        study0_.closed_date_time as closed_d3_7_0_,
        study0_.full_description as full_des4_7_0_,
        study0_.image as image5_7_0_,
        study0_.path as path6_7_0_,
        study0_.published as publishe7_7_0_,
        study0_.published_date_time as publishe8_7_0_,
        study0_.recruiting as recruiti9_7_0_,
        study0_.recruiting_updated_date_time as recruit10_7_0_,
        study0_.short_description as short_d11_7_0_,
        study0_.title as title12_7_0_,
        study0_.use_banner as use_ban13_7_0_,
        tag2_.title as title2_12_1_,
        tags1_.study_id as study_id1_10_0__,
        tags1_.tags_id as tags_id2_10_0__ 
    from
        study study0_ 
    left outer join
        study_tags tags1_ 
            on study0_.id=tags1_.study_id 
    left outer join
        tag tag2_ 
            on tags1_.tags_id=tag2_.id 
    where
        study0_.published=? 
        and (
            lower(study0_.title) like ? escape '!'
        ) 
        or exists (
            select
                1 
            from
                study_tags tags3_,
                tag tag4_ 
            where
                study0_.id=tags3_.study_id 
                and tags3_.tags_id=tag4_.id 
                and (
                    lower(tag4_.title) like ? escape '!'
                )
        ) 
        or exists (
            select
                1 
            from
                study_zones zones5_,
                zone zone6_ 
            where
                study0_.id=zones5_.study_id 
                and zones5_.zones_id=zone6_.id 
                and (
                    lower(zone6_.local_name_of_city) like ? escape '!'
                )
        )

중복은 DISTINCT을 이용하여, 제거.

 

참조:

https://cobbybb.tistory.com/18

 

[JPA] 일반 Join과 Fetch Join의 차이

JPA를 사용하다 보면 바로 N+1의 문제에 마주치고 바로 Fetch Join을 접하게 됩니다. 처음 Fetch Join을 접했을 때 왜 일반 Join으로 해결하면 안되는지에 대해 명확히 정리가 안된 채로 Fetch Join을 사용했

cobbybb.tistory.com

https://ojt90902.tistory.com/641

'SQL' 카테고리의 다른 글

Limit / offset  (0) 2023.02.03
MySql user info  (0) 2021.08.14
SQL Syntax  (0) 2021.08.03