JPA04. Fetch
포스트
취소

JPA04. Fetch

@OneToMany의 Default Fetch 전략 : Lazy

@ManyToOne의 Default Fetch 전략 : Eager

   

image

@OneToMany

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Getter @Setter
@Entity
public class Account {

    @Id @GeneratedValue
    private Long id;

    @Column(nullable=false, unique=true)
    private String username;

    private String password;

    @OneToMany(mappedBy = "owner", fetch = FetchType.EAGER) //DEFAULT: LAZY
    private Set<Study> studies = new HashSet<>();

}
1
Account result = entityManager.find(Account.class, 1L);

위 코드가 실행 시 id가 1인 Account를 가져오게 되는데, Fetch 전략에 따라 SQL 쿼리가 달라진다.

 

FetchType.LAZY

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Account 테이블에서 Account 가져옴.
select
    account0_.id as id1_0_0_,
    account0_.password as password2_0_0_,
    account0_.username as username3_0_0_ 
from
    account account0_ 
where
    account0_.id=?

// 위의 계정에 맞는 STUDY 가져오는 쿼리
select
    studies0_.owner_id as owner_id3_1_0_,
    studies0_.id as id1_1_0_,
    studies0_.id as id1_1_1_,
    studies0_.name as name2_1_1_,
    studies0_.owner_id as owner_id3_1_1_ 
from
    study studies0_ 
where
    studies0_.owner_id=?

   

FetchType.EAGER

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 조인해서 한번에 가져옴
select
    account0_.id as id1_0_0_,
    account0_.password as password2_0_0_,
    account0_.username as username3_0_0_,
    studies1_.owner_id as owner_id3_1_1_,
    studies1_.id as id1_1_1_,
    studies1_.id as id1_1_2_,
    studies1_.name as name2_1_2_,
    studies1_.owner_id as owner_id3_1_2_ 
from
    account account0_ 
left outer join
    study studies1_ 
        on account0_.id=studies1_.owner_id 
where
    account0_.id=?
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.

JPA03. 엔터티 생명주기

실행계획 - postgresql

Comments powered by Disqus.