[Mybatis] Spring mybatis, SelectKey 태그

우리는 흔히 insert 작업을 할때 (Oracle 기준입니다.)

<insert id="insert">
	insert into tbl_board(bno, title, content, writer) 
	values(seq_board.nextval, #{title},#{content},#{writer})
</insert>

위와 같이 insert를 할 것이다. bno 컬럼은 sequence 객체의 값이 들어가는 자리로 VO가 있다면 vo에 저장되어 넘어가지 않고 sequence 객체의 nextval 함수를 통해서 실행될 것이다. 

 

그런데 만약, 자동으로 추가된 PK 값을 확인해야 하는 상황이 온다면 어떻게 할까요?

- sequence 객체의 currentval 함수를 이용하면 앞으로 들어갈 PK 를 확인할 수 있는데. 임의의 갯수 임의의 번째 실행이라면? 제약사항이 있다는 것입니다.

 

<SelectKey> 태그는 PK값을 미리(before) SQL을 통해서 처리해 두고 특정한 이름으로 결과를 보관하는 방식입니다.

 

<insert id="insertSelectKey">
	<selectKey keyProperty="bno" order="BEFORE" resultType="long">
		select seq_board.nextval from dual
	</selectKey>
	insert into tbl_board(bno, title, content, writer) 
	values(#{bno}, #{title},#{content},#{writer})
</insert>

- selectKey 태그의 keyProperty 의 bno라는 네임으로 sekectKey 쿼리의 결과가 담기고

- 아래의 insert문에 그걸 꽂아줌.

댓글

Designed by JB FACTORY