예를 들어, 결제 정보를 저장하는 DB 테이블이 있다고 하자.
결제 정보를 저장하는 테이블이 결제 번호, 결제 금액, 회원 ID, 회원 이름, 가맹점 ID, 가맹점 이름으로 구성 되어 있다. 그리고 DB에 저장되는 필드명을 아주 간단하게만 써야 하는 상황이라 DB 테이블이 이렇게 구성 됐다고 한다면
PaymentInfo에서 결제 번호, 결제금액은 변수로, 회원 정보는 UserInfo 객체에 저장을 하고, 가맹점 정보는 MerchantInfo에 저장을 하려한다.
@Getter
@Setter
public class PaymentInfo{
private String paymentNo;
private BigDecimal paymentAmount;
private UserInfo userInfo;
private MerchantInfo merchantInfo;
}
@Getter
@Setter
public class UserInfo{
private String userId;
private String userName;
}
@Getter
@Setter
public class MerchantInfo{
private String merchantId;
private String merchantName;
}
<resultMap id = "PaymentInfo" type ="com.example.PaymentInfo">
<id property="paymentNo" column="PAY_NO"/>
<result property="paymentAmount" column="AMT"/>
<association property="UserInfo" javaType="com.example.UserInfo">
<result property="userId" column="USER_ID"/>
<result property="userName" column="USER_NM"/>
</association>
<association property="MerchantInfo" javaType="com.example.MerchantInfo">
<result property="merchantId" column="MERCHANT_ID"/>
<result property="merchantName" column="MERCHANT_NM"/>
</association>
</resultMap>
밑에와 같이 select문을 만들어주면 UserInfo, merchantInfo객체에 자동으로 매핑된다.
<select id="selectPaymentInfoByPaymentNo" resultMap="PaymentInfo">
SELECT PAY_NO,
USER_ID,
USER_NAME,
MCNT_ID,
MCNT_NAME
FROM PAY_INFO
WHERE PAY_NO = #{paymentNo}
</select>