스프링

Subquery returns more than 1 row

코딍코딍 2023. 3. 4. 10:39

오류 메세지

서브쿼리의 결과가 2행이상일때 발생하는 에러이다.

 

기존 코드

List<Board> boards = queryFactory
        .select(board).distinct()
        .from(board)
        .join(board.home, home).fetchJoin()
        .join(home.homeImages).fetchJoin()
        .where(board.id.eq(
                select(heart.boardId)
                        .from(heart)
                        .where(heart.userId.eq(userId))
        )).fetch();
  • where절에서 eq()로 비교를 하는데 eq는 '=' 비교이므로 서브쿼리의 결과가 1개만 반환될 경우 사용가능하기에 2개이상이 반환되면 위와 같은 오류 메세지가 발생한다.

해결

List<Board> boards = queryFactory
        .select(board).distinct()
        .from(board)
        .join(board.home, home).fetchJoin()
        .join(home.homeImages).fetchJoin()
        .where(board.id.in(
                select(heart.boardId)
                        .from(heart)
                        .where(heart.userId.eq(userId))
        )).fetch();
  • in()로 비교하여 문제를 해결하였다.