OneToOne 양방향 매핑할 때 주의할 점이 Lazy Loading이 안되는 문제이다.
출처
호오 정말 그럴까? 실험 !!
@Entity
public class Instagram {
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PLACE_ID")
public Place place;
...
}
@Entity
public class Place {
@OneToOne(fetch = FetchType.LAZY, mappedBy = "place")
public Instagram instagram;
...
}
주인: Instagram, OneToOne 양방향 매핑을 해준 상태
@Test
void test() {
Place place = placeRepository.save(new Place());
Instagram instagram = instagramRepository.save(Instagram.builder().place(place).build());
Instagram savedInstagram = instagramRepository.findById(1L).get();
}
Hibernate:
select
instagram0_.instagram_id as instagra1_4_0_,
instagram0_.created_date as created_2_4_0_,
instagram0_.modified_date as modified3_4_0_,
instagram0_.hashtag_count as hashtag_4_4_0_,
instagram0_.hashtag_name as hashtag_5_4_0_,
instagram0_.place_id as place_id6_4_0_
from
instagram instagram0_
where
instagram0_.instagram_id=?
place id만 불러온다
Lazy Loading 잘 되쥬?
이번에는 주인이 아닌 쪽을 조회해보자.
@Test
void test() {
Place place = placeRepository.save(new Place());
Instagram instagram = instagramRepository.save(Instagram.builder().place(place).build());
Place savedPlace = placeRepository.findById(1L).get();
}
Hibernate:
select
place0_.place_id as place_id1_8_0_,
place0_.created_date as created_2_8_0_,
place0_.modified_date as modified3_8_0_,
place0_.category as category4_8_0_,
place0_.kakao_id as kakao_id5_8_0_,
place0_.latitude as latitude6_8_0_,
place0_.longitude as longitud7_8_0_,
place0_.road_address_name as road_add8_8_0_,
place0_.place_name as place_na9_8_0_,
place0_.place_url as place_u10_8_0_
from
place place0_
where
place0_.place_id=?
Hibernate:
select
instagram0_.instagram_id as instagra1_4_0_,
instagram0_.created_date as created_2_4_0_,
instagram0_.modified_date as modified3_4_0_,
instagram0_.hashtag_count as hashtag_4_4_0_,
instagram0_.hashtag_name as hashtag_5_4_0_,
instagram0_.place_id as place_id6_4_0_
from
instagram instagram0_
where
instagram0_.place_id=?
주인이 아닌 쪽에 fetchType을 Lazy로 했음에도 불구하고 EagerLoading으로 조회한다.
주인이 아닌 Place는 Instagram에 대한 fk가 없기 때문에 나중에 Lazy Loading할 수 없어서 바로 불러버리는 둡