반응형

insert 쿼리를 날리고 해당 쿼리의 Primary key값을 가져오고 싶은 경우가 있는데, 불필요하게 select를 날릴 필요없이 mybatis옵션을 통해 방금 insert한 값의 pk값을 가져올 수 있다.

 

useruseGeneratedKeys, keyProperty 속성을 추가하면 처리한 paramter값에 넣어주는 것을 볼 수 있다.

<insert id="inserTableData" parameterType="java.util.HashMap" useGeneratedKeys="true" keyProperty="id">
	INSERT INTO table(
      column1,
      ...
    ) VALUES (
      #{column1},
      ...
	)
	<selectKey keyProperty="lastPk" resultType="Integer" order="AFTER">
		SELECT LAST_INSERT_ID()
	</selectKey>
</insert>

hashmap parameter를 통해 insert를 처리하였고, insert dao가 끝난 후 hashmap데이터를 확인해보면 키값으로 지정한 <selectKey>를 통해 지정한 lastPk에 값이 들어간것을 볼 수 있었다.

 

 

반응형