2.x 문서를 보면 insert를 한 후 DB에서 생성한 키값을 반환한다고 나온다.

insert

public java.lang.Object insert(java.lang.String id)


throws java.sql.SQLException
Executes a mapped SQL INSERT statement. Insert is a bit different from other update methods, as it provides facilities for returning the primary key of the newly inserted row (rather than the effected rows). This functionality is of course optional.

This overload assumes no parameter is needed.

Parameters:
id - The name of the statement to execute.
Returns:
The primary key of the newly inserted row. This might be automatically generated by the RDBMS, or selected from a sequence table or other source.
Throws:
java.sql.SQLException - If an error occurs.

하지만 iBATIS 3.0 에서는 insert 실행 후에 입력된 row의 수를 반환한다. insert로 데이터를 하나 넣으면 1이 반환되는 식이다.

당연히 2.x 처럼 생성된 PK가 Integer 로 넘어오겠거니 생각했다가, 그게 아닌걸 알고나서 "그럼 PK는 어떻게 얻어내라는건가?" 의아해하다가......insert 실행 후 로그를 찍어보니 PK 값이 설정되어 있다.

2.x 에서는 return 값으로 넘겨줬지만 3.0에서는 아예 인스턴스에 삽입해준다.
User 인스턴스 생성 시 id 프로퍼터는 null 인 상태이나 insert 실행 후 id 값이 설정되어있다.

useGeneratedKeys
Allows JDBC support for generated keys. A compatible driver is required. This setting forces generated keys to be used if set to true, as some drivers deny compatibility but still work (e.g. Derby). DEFAULT "false"

user's guide 12페이지를 보면 위와같이 적혀 있다. 즉 ibatis 설정 문서에서 아래와 같이 해주어야 mysql 과같이 db가 자동 생성한 키값을 얻어낼 수 있다.

<configuration>
    <properties resource="........../conn-info.properties"> </properties>
    <settings>
        <setting name="useGeneratedKeys" value="true"/>
    </settings>
    ....
</configuration>

이 옵션은 <insert .... userGeneratedKeys="true"> ...</insert> 에서도 쓰이는데(insert에서만 쓰임), iBATIS 설정 환경에서 false로 줬더라도 하위 수준에서 개별적인 insert 구문에 "true"를 지정하면 마찬가지로 auto generated key값을 읽어들일 수 있는 듯 하다.(테스트는 못해봤음.)

하지만 오라클같이 시퀀스를 통해서 직접 pk를 할당하는 DB들은 useGeneratedKeys 옵션과는 아무런 상관이 없다.

Posted by yeori
,