[MyBatis] 일치하지 않는 필드명-컬럼명 매핑(resultmap)

dondonee·2024년 4월 6일
0

일치하지 않는 필드명-컬럼명 매핑

RDB에서는 post 테이블의 ID 컬럼명이 post_id이고 자바에서는 Post 클래스의 필드명을 id로 사용하여 마이바티스에서 매핑되지 않는 문제가 생겼다.


ResultMap 작성

매퍼에서 <resultMap>을 사용하여 직접 매핑을 시켜주어야 한다.

    <resultMap id="postmap" type="Post">
        <id property="id" column="post_id"/>
        <result property="categoryId" column="category_id"/>
        <result property="authorId" column="author_id"/>
        <result property="title" column="title"/>
        <result property="content" column="content"/>
        <result property="dateRegistered" column="date_registered"/>
        <result property="dateModified" column="date_modified"/>
        <result property="viewCount" column="view_count"/>
    </resultMap>

    <insert id="insert" useGeneratedKeys="true" keyProperty = "id" parameterType="Post">
        INSERT INTO post (category_id, author_id, title, content, date_registered, view_count)
            VALUES (#{categoryId}, #{authorId}, #{title}, #{content}, #{dateRegistered}, #{viewCount})
    </insert>
    
    <select id="selectById" resultMap="postmap">
        SELECT * FROM post WHERE post_id = #{id}
    </select>
  1. <resultMap> 만들기
    • id : resultMap을 구분하기 위한 ID. 임의대로 작성.
    • type : 매핑할 자바 객체. 나는 프로퍼티스 파일에서 mybatis.type-aliases-package 속성을 지정했기 때문에 패키지는 생략했다.
    • <id> : 기본키 매핑
    • <result> : 일반 컬럼 매핑
  2. 사용하는 메서드에 resultMap 속성 추가(id 지정).


테스트

@Test
void insertTest() {
	//given
	Post post = new Post(1L, 1L, "title", "content");

	//when
	Post insertPost = postRepository.insert(post);

	//then
	Post selectPost = postRepository.selectById(insertPost.getId());
	assertThat(selectPost).isEqualTo(insertPost);
}

필드명과 컬럼명이 일치하지 않지만 <resultMap>으로 매핑시켜 주었더니 정상적으로 SELECT 조회가 된다. 👍




🔗 Reference

0개의 댓글