JPA는 연관관계가 설정된 Entity의 정보를 바로 가져올지, 필요할 때 가져올지 정할 수 있습니다.
LAZY, 다른 하나는 EAGER 입니다.LAZY는 지연 로딩으로 필요한 시점에 정보를 가져옵니다.EAGER는 즉시 로딩으로 이름의 뜻처럼 조회할 때 연관된 모든 Entity의 정보를 즉시 가져옵니다.이름 뒤쪽이 Many일 경우 효율적으로 정보를 조회하기 위해
지연 로딩이 default로 설정되어있습니다.
이름 뒤쪽이 One일 경우 해당 Entity 정보가 한 개만 들어오기 때문에 즉시 정보를 가져와도 무리가 없어즉시 로딩이 default로 설정되어있습니다.
지연 로딩도 마찬가지로 영속성 컨텍스트의 기능 중 하나입니다.
따라서 지연 로딩된 Entity의 정보를 조회하려고 할 때는 반드시 영속성 컨텍스트가 존재해야합니다.
‘영속성 컨텍스트가 존재해야한다’라는 의미는 결국 ‘트랜잭션이 적용되어있어야 한다’라는 의미와 동일합니다.
지연로딩을 사용하려면 영속성 컨텍스트가 필요하다.
transactional 필요.
@Transactional(readOnly = true)
public Page<ProductResponseDto> getProducts(User user, int page, int size, String sortBy, boolean isAsc) {
Sort.Direction direction = isAsc ? Sort.Direction.ASC : Sort.Direction.DESC;
Sort sort = Sort.by(direction, sortBy);
Pageable pageable = PageRequest.of(page, size, sort);
UserRoleEnum userRoleEnum = user.getRole();
Page<Product> productList;
if (userRoleEnum == UserRoleEnum.USER) {
productList = productRepository.findAllByUser(user, pageable);
} else {
productList = productRepository.findAll(pageable);
}
return productList.map(ProductResponseDto::new);
}
성능향상을 위해 read only 사용.