본문 바로가기
카테고리 없음

OneToOne Lazy Loading

by 수수남매 2023. 11. 27.
  • 막연하게 OneToOne 연관관계인 경우 Lazy Loading을 설정해도 Eager가 적용된다고 알고 있다가
  • 외래 키의 주인은 Lazy Loading이 된다는 글을 보고 테스트해 봄

  • Lazy Loading 적용 전
@OneToOne
@JoinColumn(name = "account_id")
private Account account;
  • 결과
Hibernate: 
    select
        s1_0.id,
        s1_0.account_id,
        s1_0.address,
        s1_0.name,
        s1_0.tel 
    from
        store s1_0 
    where
        s1_0.name like ? escape '\\'
Hibernate: 
    select
        a1_0.id,
        a1_0.address,
        a1_0.email,
        a1_0.password,
        a1_0.phone,
        a1_0.point,
        a1_0.role,
        s1_0.id,
        s1_0.address,
        s1_0.name,
        s1_0.tel 
    from
        account a1_0 
    left join
        store s1_0 
            on a1_0.id=s1_0.account_id 
    where
        a1_0.id=?
Hibernate: 
    select
        a1_0.id,
        a1_0.address,
        a1_0.email,
        a1_0.password,
        a1_0.phone,
        a1_0.point,
        a1_0.role,
        s1_0.id,
        s1_0.address,
        s1_0.name,
        s1_0.tel 
    from
        account a1_0 
    left join
        store s1_0 
            on a1_0.id=s1_0.account_id 
    where
        a1_0.id=?
  • Lazy Loading 적용 후
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "account_id")
private Account account;
  • 결과
Hibernate: 
    select
        s1_0.id,
        s1_0.account_id,
        s1_0.address,
        s1_0.name,
        s1_0.tel 
    from
        store s1_0 
    where
        s1_0.name like ? escape '\\'
  • account Entity의 경우 IDE에서 친절하게 Lazy해도 Eager적용이라고 알려줌
  • 따라서 로그인만 해도 기본 2쿼리 발생, 해결방법은 fetch join 하지만 고객 account의 경우 연관된 store가 없음
  • 결과 - 고객 account의 경우 연관 store가 없어 에러 발생함, 사장 account의 경우 로그인 성공