생계유지형 개발자/Spring Framework

[Spring/Mybatis] Select 결과를 결과타입 내 다른 객체에 매핑

이 가을 2021. 6. 21. 16:01

 

Mybatis 문법에서 <select/>의 결과 컬럼을 resultType 또는 resultMap 속성에 객체명 또는 매퍼 id를 정의하여 특정 DTO(Data Type Object)에 매핑한다.

예를 들어, SELECT a, b, c, d FROM table 쿼리를 실행할 때, DTO 객체에 a, b, c, d라는 필드가 있으면 알아서 매핑이 된다.

이때 a, b, c, d라는 각각의 컬럼 또는 필드가 서로 데이터 타입이 일치해야한다.

데이터 타입이 상이하고 오토캐스팅에 실패하면 오류가 발생한다.

그리고 기본적으로 int, boolean, double 등의 기본 자료형과  String, Integer 등과 같은 자료형 객체일 때 매핑이 된다.

 

하지만 모든 사용자 정의 객체(여기선 DTO)가 기본타입의 필드만 가지고 있는 것은 아니며, 자료형이 사용자 정의 객체인 필드를 가질 수 있다.

예를 들어, Banner 클래스는 기본 자료형을 갖는 id, name 필드 외에 AttachFile 객체 타입의 attachFile 필드가 있다.

@Getter
@Setter
class Banner {
private long id;
    private String name;
    private AttachFile attachFile;
}

@Getter
@Setter
class AttachFile {
private long id;
    private String originName;
    private String downloadLink;
    private String readLink;
}

그리고 banner 테이블과 attach_file 테이블을 조인해서 배너의 이미지 정보를 함께 조회하는 쿼리가 있다.

select b.id,
    b.name, 
    a.origin_name, 
    a.download_link, 
    a.read_link
from banner b 
    left join attach_file a on (b.attach_file_id = a.id)

Mybatis에서 위의 쿼리를 실행해서 Banner 데이터를 조회한 후 Banner 객체에 매핑하고자 한다.

<select id="selectBannerList" resultMap="bannerResultMap">
select b.id,
    b.name, 
    a.origin_name, 
    a.download_link, 
    a.read_link
from banner b 
    left join attach_file a on (b.attach_file_id = a.id)
</select> 

<resultMap id="bannerResultMap">
	<id column="id" property="id"/>
        <result column="b.id" property="id"/>
        <result column="name" property="name"/>
        <result column="origin_name" property="attachFile.originName"/>
        <result column="download_link" property="attachFile.downloadLink"/>
        <result column="read_link" property="attachFile.readLink"/>
</resultMap>

<select/> 요소 정의 시 resultType="Banner" 속성을 정의하면 b.id, b.name 컬럼은 Banner 객체의 id와 name에 알아서 매핑이 될 것이다.

반면에, a.origin_name, a.download_link, a.read_link 컬럼을 Banner 객체의 attachFile에 매핑하기 위해서는 resultMap 속성을 사용한다.

attachFile은 Banner 클래스의 AttachFile 타입 필드이고, AttachFile 클래스에 originalName, downloadLink, readLink에 결과를 매핑하기 위해 위와 같이 resultMap을 정의한다.