개념 및 사용 이유
sql 수행 작업 중 insert된 이후에 알 수 있는 값을 가져와서 select 쿼리를 보낼 때 사용한다.
주로 생성하고 나서 인덱스 번호를 가져와 작업하는 상황에서 사용한다.
속성
- keyProperty : selectKey 구문의 결과가 셋팅될 대상 프로퍼티
- keyColumn : 리턴되는 결과셋의 칼럼명은 프로퍼티에 일치, 여러개를 사용한다면 콤마를 사용해서 구분
- resultType : 결과의 타입
- order : BEFORE, AFTER를 셋팅할 수 있음 (BEFORE은 키를 먼저 조회하고 그 값을 키프로퍼티에 셋팅한 뒤 insert 구문 실행 - 오라클, AFTER은 insert구문 실행한 뒤 selectKey 구문 실행 - mysql)
- statementType : STATEMENT, PREPARED, CALLABLE 중 선택 가능
예시
insert 이전, 키 값을 조회 (oracle)
<insert id="insertTest" parameterType="String">
<selectKey keyProperty="testId" resultType="int" order="BEFORE">
SELECT MAX(id)+1 FROM test
</selectKey>
INSERT INTO test(test_id, test_name)
VALUES (#{testId}, #{testName})
</insert>
-> #{testId}에는 selectKey로 조회한 값이 들어감
insert 이후, 키 값을 조회 (mysql)
<insert id="insertTest" parameterType="String">
INSERT INTO test(test_name)
VALUES (#{testName})
<selectKey keyProperty="testId" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
<insert id="insertTest2" parameterType="test">
INSERT INTO test2(test2_id, test2_name)
VALUES (#{testId}, #{test2Name})
</insert>
-> selectKey로 받아온 testId를 이후 insert 쿼리를 실행할 때 사용한다.