인프런 커뮤니티 질문&답변

차가운물님의 프로필 이미지

작성한 질문수

실전! 스프링 부트와 JPA 활용2 - API 개발과 성능 최적화

주문 조회 V1: 엔티티 직접 노출

orderItem LAZY 로딩 질문

21.06.22 13:58 작성

·

289

0

안녕하세요. 

  • orderItems.stream().forEach(o -> o.getItem().getName());

orderItem 반복문 돌 때 getName을 하거나 getprice, getstockQuantity를 넣어도 모든 필드가 로딩이 되는데 왜 그런건지 이해가 잘 안가는데 간단한 설명 부탁드려도 될까요?

답변 1

3

David님의 프로필 이미지

2021. 06. 22. 22:45

안녕하세요. Jeongmin Lee님:), 공식 서포터즈 Taewon David Hwang입니다.

지연로딩(Lazy Loading)은 엔티티의 애트리뷰트에 접근할 때 데이터를 가져옵니다.

그러나 하이버네이트에서 지정한 기본타입에 해당되는 것들은 기본적으로 지연로딩을 허용하지 않습니다.

따라서 OrderItem의 애트리뷰트인 name, price, stockQuantty 중 하나라도 접근하게 되면 기본타입에 해당하는 name, price, stockQuantity의 데이터를 모두 불러오게 됩니다.

따라서 모든 필드가 로딩되는 것처럼 느끼시는 겁니다.

만약 애트리뷰트가 기본타입이 아니라면 Lazy Loading이 적용될 수 있습니다. OrderItem에 임의의 필드(ex. List<ItemOption> itemOptions)를 추가하시고 Lazy Loading을 걸어보시면 OrderItem에서 getName()을 하더라도 Lazy Loading을 설정해둔 필드(itemOptions)는 내부적으로 값을 불러오지 않는 것을 알 수 있습니다.

감사합니다.

참고

* https://docs.jboss.org/hibernate/orm/5.5/userguide/html_single/Hibernate_User_Guide.html#basic-annotation

fetch - FetchType (defaults to EAGER)

Defines whether this attribute should be fetched eagerly or lazily. JPA says that EAGER is a requirement to the provider (Hibernate) that the value should be fetched when the owner is fetched, while LAZY is merely a hint that the value is fetched when the attribute is accessed. Hibernate ignores this setting for basic types unless you are using bytecode enhancement. See the Bytecode Enhancement for additional information on fetching and on bytecode enhancement.