spring/mybatis

[mybatis] resultmap collection 사용

겸쨔 2024. 7. 22. 15:12
반응형

안녕하세요.

mybatis로 데이터를 조회할 때 1:N 구조로 매핑할 때가 있죠?

이럴 땐 resultmap과 collection을 사용해서 편리하게 매핑할 수 있어요.

 

먼저 collection을 사용하기 전의 select 쿼리를 볼게요.

리턴 타입을 dto로 박아놨죠?

<select id="selectBoardList" resultType="BoardDto">
    SELECT
        board_id,
        title,
        content
    FROM
        board
</select>


이렇게만 하면 쿼리 조회 결과가 게시글 리스트로 반환돼요.

하지만 게시글의 댓글을 BoardDto의 List<ReplyDto> 에 매핑하고 싶잖아요.

 

그럼 이렇게 하시면 돼요.

<resultMap id="selectCommentListMap" type="BoardDto">
	<collection select="selectCommenList" column="{boardId=board_id}" javaType="java.util.ArrayList" ofType="CommentDto">
    	<result column="content" property="commentList"/>
    </collection>
</resultMap>

<select id="selectBoardList" resultMap="selectCommentListMap">
    SELECT
        board_id,
        title,
        content
    FROM
        board
</select>

<select id="selectCommentList" resultType="CommentDto">
    SELECT
        content
    FROM
        comment
    WHERE
    	board_id = #{boardId}
</select>

유심히 보셔야할건 selectBoardList의 resultType이 아니라 resultMap으로 변경되었구요.

해당 resultMap에 들어가는 녀석은 맨 위에 정의되어 있는 reusltMap의 id에요.

저 reusltMap의 type은 기존에 받으려고 했던 dto구요.

 

여기서 collection 태그를 넣어야 List로 받는거 같더라구요.

해당 collection의 select에는 돌리고 싶은 select 쿼리의 id를 넣으면 돼요.

그리고 collection의 column은 해당 select 문으로 넘기고 싶은 selectBoardList의 조회 결과로 나온 board_id구요.

마지막으로 collection 태그 안에 result는 뽑고 싶은 프로퍼티를 넣으시면 될거에요.

 

result의 column은 selectCommentList의 조회 쿼리의 결과로 나온 녀석의 이름을 넣으시면 되구요.

result의 property에는 받으려는 BoardDto의 commentList 변수명을 넣으시면 매핑해줘요.

 

 

dto는 이렇게 구성되어 있어요.

public class BoardDto {
	private Integer boardId;
    private String title;
    private String content;
    private List<CommentDto> commentList;
}

public class CommentdDto {
    private String content;
}

 

그.. 이해가 잘 안 되실수도 있어요.

제가 잘 안 됐었거든요.

 

이해 안 되시면 댓글 남겨주세요..

반응형