Bactoria 황준오

JPA04. Fetch

2019-06-10
bactoria
JPA

@OneToMany의 Default Fetch 전략 : Lazy

@ManyToOne의 Default Fetch 전략 : Eager

   

image

@OneToMany

@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<>();

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

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

 

FetchType.LAZY

// 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

// 조인해서 한번에 가져옴
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=?

황준오 (Bactoria) 황준오 (Bactoria)

.

Comments

Content