JPA 프로그래밍 6. Fetch - KwangtaekJung/inflearn-spring-data-jpa-keesun GitHub Wiki

JPA 프로그래밍: Fetch

연관 관계의 엔티티를 어떻게 가져올 것이냐... 지금 (Eager)? 나중에(Lazy)?

  • @OneToMany의 기본값은 Lazy
  • @ManyToOne의 기본값은 Eager
        ...
        Session session = entityManager.unwrap(Session.class);
        Post post = session.get(Post.class, 4l);
        System.out.println("===================");
        System.out.println(post.getTitle());

        post.getComments().forEach( c -> {
            System.out.println("--------------");
            System.out.println(c.getComment());
        });
Hibernate: 
    select
        post0_.id as id1_2_0_,
        post0_.title as title2_2_0_ 
    from
        post post0_ 
    where
        post0_.id=?

Hibernate: 
    select
        comments0_.post_id as post_id4_1_0_,
        comments0_.id as id1_1_0_,
        comments0_.id as id1_1_1_,
        comments0_.comment as comment2_1_1_,
        comments0_.post_id as post_id4_1_1_,
        comments0_.title as title3_1_1_ 
    from
        comment comments0_ 
    where
        comments0_.post_id=?

의도한 바와는 다르게 N + 1 문제가 재현 되지 않았다. Hibernate가 똑똑해졌다???

참고로 쿼리 파라미터를 확인해보기 위해 다음 의존성 및 설정을 추가하자.

		<dependency>
			<groupId>com.github.gavlyukovskiy</groupId>
			<artifactId>p6spy-spring-boot-starter</artifactId>
			<version>1.7.1</version>
		</dependency>
#System.out에 출력한다. 운영환경에서는 사용하면 안됨.
#spring.jpa.show-sql=true

# SQL을 좀 더 가독성 좋게 보여준다.
spring.jpa.properties.hibernate.format_sql=true

#System.out이 아닌 로거에 출력하자.
logging.level.org.hibernate.SQL=debug

#쿼리 파라미터를 보여준다. => 보기 불편하다. 외부 라이브러리 사용하자.p6spy
logging.level.org.hibernate.type.descriptor.sql=trace

#application.properties 에 다음으로 설정이 가능하다.(기본설정이기 때문에 설정을 생략해도 된다)
decorator.datasource.p6spy.enable-logging=true
⚠️ **GitHub.com Fallback** ⚠️