🤔문제
주 테이블의 상세 정보를 가져오는 코드에서 연관 데이터가 없으면 주 테이블의 정보도 반환되지 않는 문제 발생
❗원인
주 테이블 id로 연관 테이블을 조회할 때 join을 사용
@Query("SELECT r FROM Restaurant r join fetch r.ratingList WHERE r.id = :id")
Optional<Restaurant> findByIdWithRatingsUsingFetchJoin(@Param("id") Long id);
default Restaurant getById(Long id) {
return findByIdWithRatingsUsingFetchJoin(id)
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND));
}
💡해결방법
left join을 사용하자!
- Join
- 일반적으로 Inner Join을 수행
- 만약 주 테이블(’Restaurant’)과 연결 테이블(’Rating’)사이에 일치하는 데이터가 없을 경우, 해당 주 테이블의 레코드는 결과 집합에서 제외
- 이로 인해 ‘Restaurant’가 ‘ratingList’와 관련된 데이터가 없는 경우 ‘NoResultException’ 또는 비어있는 결과가 발생할 수 있음
- Left Join
- ‘Restaurant’와 ‘Rating’ 사이에 일치하는 데이터가 없더라도 주 테이블(’Restaurant’)의 레코드는 결과 집합에 포함
- ‘Rating’과 관련된 데이터가 없는 경우, ‘Rating’ 엔티티 관련 부분은 ‘null’로 설정됨
따라서 ‘join’을 사용하면 연결된 데이터가 없을 때 결과가 발생하지 않고, ‘left join’을 사용하면 연결된 데이터가 없더라도 주 테이블(’Restaurant’)의 데이터는 반환된다.
'TIL' 카테고리의 다른 글
[TIL][Spring] javax.xml.bind.DatatypeConverter 에러 (0) | 2023.12.21 |
---|---|
[TIL][SQL] @Modifying 어노테이션 (0) | 2023.11.08 |
JPA 에서 복합키 사용하기 (0) | 2023.08.06 |
[TIL][ContentProject] h2-console 403 error (0) | 2023.07.27 |
[TIL][ContentProject] H2 DB 에서 User Table 사용하기 (0) | 2023.07.19 |