iBatis에서 myBatis로 넘어오면서 selectKey에서 last_insert_id 를 가져오는 방식에 변화가 생겼습니다.

기존 iBatis 방식으로 넘겨받으면 1만 넘어오는데, 이는 increase된 selectKey 가 아닌 inserted row count 입니다.
myBatis에서는 insert시 전달받은 parameter class에 keyProperty로 정의한 값 또는 object로 자동으로 inject 됩니다.

이전 iBatis에서도 그랬는지는 기억이 가물가물하네요. 암튼 경험한 부분을 명시합니다.

 

간단한 예를 들어서 설명합니다.

 

<insert id="insertUser" parameterMap="map">
    INSERT INTO USER (
      NAME, ID, PW 

    )VALUES(
        #{NAME}, #{ID}, #{PW}
    )
<selectKey keyProperty="USER_IDX" resultClass="java.lang.Integer">
    SELECT LAST_INSERT_ID()
</selectKey>
</insert>

 

int insertRowCnt = userMapper.insertUser(map);
int userIdx = map.get("USER_IDX");


다시말해서 위와 같은 방법으로 가져와야 합니다.

 

이전 iBatis에서는 아래와 같이 요청해도 last_insert_id를 리턴해줬던것 같았는데...

int userIdx = userMapper.insertUser(map);

 

만약 map 대신 POJO클래스(UserObject 같은)를 사용한다면 pojo 형태로 keyProperty를 정의합니다.

 

<insert id="insertUser" parameterType="UserObject">
INSERT INTO USER (
  NAME,  ID, PW
)VALUES(
  #{name},  #{id}, #{pw}
)
<selectKey keyProperty="userIdx" resultClass="java.lang.Integer">
    SELECT LAST_INSERT_ID()
</selectKey>
</insert>


int insertRowCnt = userMapper.insertUser(userObject);
int userIdx = userObject.getUserIdx(); <==

 

결론 : 변수로 넘겨준 class에 자동으로 injection된다는 것.

차라리 iBatis를  경험하지 않았더라면 이해가 더 빨랐을 수도 있을것 같습니다. 그저 비슷하려니 하는 막연함이 부른 삽질.

아니면 이전부터 있었던 동일한  기능이었는데, 제대로 알지 못하고 사용했는지도 모르겠습니다. 집에가서 iBatis 책을 찾아봐야겠습니다.

 

이글을 읽는 분들은 부디 저처럼 삽질하지 마시길 바랍니다. 화이팅~