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 (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
    )

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