querydsl문으로 두번째 깊이(depth)를 fetch 해보자!

Jinseok Lee·2021년 9월 22일
3

사연

채팅내역(ChattingHistory) > 전송자(User) > 전송자의 추가정보(AdvertiserInfo)를 fetch해서 한 번에 가져오고 싶었지만 전송자의 추가정보가 계속해서 null값으로 떨어지고 있었다.

@Entity
public class ChattingHistory extends BaseTimeEntity {

    ...
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User sender;

    ....

}

@Entity
public class User extends BaseTimeEntity {
    
    ....

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "advertiser_info_id")
    private AdvertiserInfo advertiserInfo;

    ....
    
}

querydsl (해결 전)

    @Override
    public Page<ChattingHistory> findPageByCondition(Pageable pageable, ChattingHistoryCondition condition) {
        return applyPagination(pageable,
            contentQuery -> contentQuery
            .selectFrom(chattingHistory)
            .where(
                chattingRoomIdEq(condition.getChattingRoomId())
            )
        );
    }

leftJoin이 빠져있는 모습이다.

querydsl (해결 후)

    @Override
    public Page<ChattingHistory> findPageByCondition(Pageable pageable, ChattingHistoryCondition condition) {
        return applyPagination(pageable,
            contentQuery -> contentQuery
            .selectFrom(chattingHistory)
                .leftJoin(chattingHistory.sender, user).fetchJoin()
                .leftJoin(user.advertiserInfo, advertiserInfo).fetchJoin()
            .where(
                chattingRoomIdEq(condition.getChattingRoomId())
            )
        );
    }

leftJoin을 chain형태로 이어서 작성하니까 chattingHistory.sender.advertiserInfo가 fetch 되어서 불러와 지는 것을 확인할 수 있었다.

profile
전 위메프, 이직준비중

0개의 댓글