[Spring] 스프링 Mapper.xml (mybatis)

Hannana·2024년 10월 1일

스프링 코드에서 mysql 쿼리문을 사용할 수 있게 해주는
가장 기본적인 xml구조에 대해 공부하기 💬


    <select id="get" resultMap="memberMap">
        select m.username, password, email, reg_date, update_date, auth
        from tbl_member m
            left outer join tbl_member_auth a
            on m.username = a.username
        where m.username = #{username}
    </select>

위의 결과가 아래와 같이 나옴

<resultMap id="memberMap"  type="MemberVO">
        <id property="username" 		column="username" />
        <result property="username"		column="username" />
        <result property="password"		column="password" />
        <result property="email" 		column="email" />
        <result property="regDate"		column="reg_date" />
        <result property="updateDate"	column="update_date" />

        <collection property="authList" resultMap="authMap" />
    </resultMap>

여기서 resultMap 하위 태그를 구분하자면,

  • id : 테이블의 id값
  • result : 테이블의 일반 컬럼
  • collection : 테이블의 리스트 컬럼

즉 막줄의 매핑은

한 사용자(MemberVO)가 여러 개의 권한(AuthVO)을 가질 수 있음
= 여러개의 권한은 테이블의 authList컬럼으로 표시 됨
= authList컬럼은 여러 개의 AuthVO으로 구성됨.

<resultMap id="authMap" type="AuthVO">
        <result property="username" column="username" />
        <result property="auth" 	column="auth" />
    </resultMap>

또 그 AuthVO는 username과 auth 두 개의 컬럼으로 구성됨

<mapper namespace="com.~~.mapper.UserDetailsMapper">

    <resultMap id="authMap" type="AuthVO">
        <result property="username" column="username" />
        <result property="auth" 	column="auth" />
    </resultMap>

    <resultMap id="memberMap"  type="MemberVO">
        <id property="username" 		column="username" />
        <result property="username"		column="username" />
        <result property="password"		column="password" />
        <result property="email" 		column="email" />
        <result property="regDate"		column="reg_date" />
        <result property="updateDate"	column="update_date" />

        <collection property="authList" resultMap="authMap" />
    </resultMap>

    <select id="get" resultMap="memberMap">
        select m.username, password, email, reg_date, update_date, auth
        from tbl_member m
            left outer join tbl_member_auth a
            on m.username = a.username
        where m.username = #{username}
    </select>
</mapper>

이 xml mapper 파일이
이제 mapper 인터페이스와 매핑된다.


public interface UserDetailsMapper {
    MemberVO get(String username);
}

쿼리문의 id가 함수명으로 온 것을 확인할 수 있음

profile
(구) https://hansjour.tistory.com/ 이사옴. 성장하는 하루를 쌓아가는 블로그

0개의 댓글