티스토리 뷰

spring boot/snippets

n+1 이슈 피하기

lingi04 2021. 12. 22. 23:10

querydsl 사용할 경우

public Page<Item> findItemBy(SearchItemClause clause, Pageable pageable) {
    QueryResults<Item> results = jpaQueryFactory.select(QItem.item)            
        .from(item)
        .where(clause.whereClause())
        .distinct()
        .offset(pageable.getOffset())
        .limit(pageable.getPageSize())
        .fetchResults();

    results.getResults().stream().map(Item::getSubItem).forEach(Hibernate::initialize);

    return new PageImpl<>(results.getResults(), pageable, results.getTotal());
}

이런 식으로 부모 객체만 조회한 후 자식 객체를 불러와 Hibernate::initialize 메소드를 사용하면

-- 쿼리
select
    count(distinct item.detect_option_game_seq) as col_0_0_ 
from
    ITEM item

select
    distinct item.id,
    item.create_time,
    item.create_user,
    item.update_time,
    item.update_user
from
    ITEM item limit ?

select
    subItem.id,
    subItem.name
    subItem.itemId
from
    SUB_ITEM subItem 
where
    subItem.itemId in (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
    )

이렇게 부모 객체에 속한 자식 객체들을 한번에 불러온다.

'spring boot > snippets' 카테고리의 다른 글

mocking 하는 방법  (0) 2021.12.22
jpa에서 json column 사용하기  (0) 2021.12.22
entity에 enum list 정의하기  (0) 2021.12.22
jpa repository만 테스트  (0) 2021.12.22
jpa entity에서 column 정의  (0) 2021.12.22
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday