본문 바로가기
mybatis

mybatis - insert 후 해당 객체의 바로 PrimaryKey 얻기

by khds 2023. 4. 16.

 

mybatis를 진행하면서 객체를 데이터베이스에 저장하는 메서드를 실행 후 데이터베이스 상의 primaryKey가 바로 필요한 경우가 있다.

mybatis에서는 insert, delete, update 후 int 값을 리턴하는데 이 값은 얼마나 insert, delete, update 한 지를 알려주는 count 값이다. 

insert 한 후 id를 얻기 위해서 select 메서드를 실행해야 하는가? 이는 데이터베이스에 한번 접근할 것을 두번이나 접근해야 하므로 좋지 않다. 

그렇다면 어떻게 해야하는가? 

방법은 xml파일을 활용하는 것이다.

아래의 예시를 보자.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="foot.footprint.domain.article.dao.CreateArticleRepository">
  <insert id="saveArticle" parameterType="Article" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO article(
    content, latitude, longitude, public_map, private_map, title, create_date, member_id
    ) VALUES (#{content}, #{latitude}, #{longitude}, #{public_map}, #{private_map}, #{title},
    #{create_date}, #{member_id})
  </insert>
</mapper>

 

insert 태그에 속성에에서 중요한 것은 useGenerateKeys와 keyProperty이다. 

useGenerateKeys는 true로 설정하고 ketProperty는 어떤 값을 가져올지(PrimaryKey) 필드 명을 적으면 모두 끝난다.

정말 간단하지 않는가?

 

하지만 주의할 점이 있다.

JPA를 많이 다뤘다면 헷갈릴 사항이 있다.

해당 메서드의 리턴이 객체 그 자체 혹은, primaryKey라고 착각하는 것이다. 

나도 리턴 값이 계속 primaryKey라고 믿어서 많이 헤맨 경험이 있다.

primaryKey를 얻는 방법은 insert 할 때 집어넣은 객체의 get함수를 사용하면 얻을 수 있다.

원래는 값이 없었는데 메서드를 실행함으로써 생긴 것이다. 

 

아래는 예시코드이다.

@Test
  public void saveArticle() {
    //given
    Long memberId = saveOne(); // member 객체를 만들고 memberId를 리턴하는 메서드
    Article article = buildArticle(memberId);

    //when & then
    assertThat(article.getId()).isNull();
    articleRepository.saveArticle(article);

    //then
    assertThat(article.getId()).isNotNull();
  }