fetch join
- Spring Data JPA 에서 fetch join 이용
- Querydsl 에서 fetch join 이용
- Entity 연관관계 구조
- BOOK_REVIEW와 USER_INFO가 ManyToOne관계
- BOOK_REVIEW와 BOOK이 ManyToOne관계
- BOOK을 조회하면 리뷰와 회원 정보가 포함된 결과값을 얻는코드를 작성.
- BOOK -> BOOK_REVEIW, USER_INFOR
@Repository
public interface BookRepository extends CrudRepository<Book, String>, BookRepositoryCustom{
@Query(value = "select b from Book b " +
"join fetch b.bookReviewList br " +
"join fetch br.userInfo where b.isbn = :isbn")
Book findByIsbnWithReview(@Param("isbn")String isbn);
}
public class BookRepositoryImpl implements BookRepositoryCustom{
private final JPAQueryFactory queryFactory;
public BookRepositoryImpl(EntityManager entityManager) {
this.queryFactory = new JPAQueryFactory(entityManager);
}
@Override
public Book findByIsbnWithReview(String isbn) {
return queryFactory
.selectFrom(book)
.join(book.bookReviewList, bookReview).fetchJoin()
.join(bookReview.userInfo).fetchJoin()
.where(book.isbn.eq(isbn))
.fetchOne();
}
}
- fetch 종류 - 결과 반환 결정
- fetch : 조회 대상이 여러건일 경우. 컬렉션 반환
- fetchOne : 조회 대상이 1건일 경우(1건 이상일 경우 에러). generic에 지정한 타입으로 반환
- fetchFirst : 조회 대상이 1건이든 1건 이상이든 무조건 1건만 반환. 내부에 보면 return limit(1).fetchOne() 으로 되어있음
- fetchCount : 개수 조회. long 타입 반환
- fetchResults : 조회한 리스트 + 전체 개수를 포함한 QueryResults 반환. count 쿼리가 추가로 실행된다.
select
book0_.isbn as isbn1_2_0_,
bookreview1_.review_no as review_n1_3_1_,
userinfo2_.user_no as user_no1_7_2_,
book0_.author as author2_2_0_,
book0_.book_name as book_nam3_2_0_,
book0_.category as category4_2_0_,
book0_.contents as contents5_2_0_,
book0_.book_image as book_ima6_2_0_,
book0_.kdc as kdc7_2_0_,
book0_.keyword as keyword8_2_0_,
book0_.publisher as publishe9_2_0_,
bookreview1_.isbn as isbn7_3_1_,
bookreview1_.create_date as create_d2_3_1_,
bookreview1_.declaration as declarat3_3_1_,
bookreview1_.rating as rating4_3_1_,
bookreview1_.review_contents as review_c5_3_1_,
bookreview1_.review_status as review_s6_3_1_,
bookreview1_.user_no as user_no8_3_1_,
bookreview1_.isbn as isbn7_3_0__,
bookreview1_.review_no as review_n1_3_0__,
userinfo2_.del_date as del_date2_7_2_,
userinfo2_.delete_reason as delete_r3_7_2_,
userinfo2_.last_connection as last_con4_7_2_,
userinfo2_.user_birth as user_bir5_7_2_,
userinfo2_.user_gender as user_gen6_7_2_,
userinfo2_.user_id as user_id7_7_2_,
userinfo2_.user_name as user_nam8_7_2_,
userinfo2_.user_priority as user_pri9_7_2_,
userinfo2_.user_pw as user_pw10_7_2_,
userinfo2_.user_status as user_st11_7_2_
from
book book0_
inner join
book_review bookreview1_
on book0_.isbn=bookreview1_.isbn
inner join
user_info userinfo2_
on bookreview1_.user_no=userinfo2_.user_no
where
book0_.isbn=?