Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

자바나라

[Mybatis] 방금 Insert한 row를 select 하고 싶을 때 : selectKey 본문

오늘 배운 자바

[Mybatis] 방금 Insert한 row를 select 하고 싶을 때 : selectKey

주데브 2018. 5. 2. 17:03

기존 방식으로 mybatis에서 insert 쿼리문을 사용할 때,


1
2
3
4
5
6
7
<insert id="insert" parameterType="guestVO" > 
 
    insert into guest_tbl
    values(seq_guestbook.nextval,#{name},#{password},#{content},sysdate)    
       
</insert>
 
cs



sequence.nextval 값을 테이블에 직접 넣어주었다.

그러나 이러한 insert방식에서는 내가 방금 insert한 row를 다시 select 하는 것에 어려움이 있다.


이럴때 필요한 것이 selectKey이다.



1
2
3
4
5
6
7
8
9
10
11
12
<insert id="insert" parameterType="guestVO" >
    <selectKey keyProperty="no" resultType="int" order="BEFORE">  
        select seq_guestbook2.nextval FROM dual
     </selectKey>
    
    insert into guest_tbl
    values(#{no},#{name},#{password},#{content},sysdate)    
          
</insert>
 
cs


<insert> 안에 <selectKey>를  넣어주면 sequence를 만들어서 그 결과값을 no에 대입시켜준다.


 <selectKey keyProperty="no" resultType="int" order="BEFORE"> 


이 문장에서 keyProperty는 내가 가진 guestVO(객체)의 no 와 변수이름이 일치해야 하며,

     resultType은 no의 type과 일치해야 제대로 setter가 작동하여 대입된다.

order는 아래의 insert 쿼리문 이전(before) 또는 이후(after)에 작업할지를 설정할 수 있다.

 

<selectKey> 태그가 제대로 작동한다면 

insert를 실행할 때마다 sequence 값이 1씩 증가하며 GuestVO 객체의 no라는 변수에 차곡차곡 set(대입)될 것이다.


 
    insert into guest_tbl
    values(#{no},#{name},#{password},#{content},sysdate)  


따라서 이 문장에서  #{no} 를 통해  no 값을 get(호출) 하여 첫번째 컬럼에 넣어줄 수 있으며

DAO나 service에서도 no 값을 불러다가 쓸 수 있다.

->  방금 insert한 row를 no를 통해 불러다 쓰기 용이해진다.




sqlSession.insert("cateDB.insert",vo);
System.out.println(vo.getCateNo());
return vo.getCateNo();


 xml에서 select key를 변수 이름만 잘 맞춰주면 vo에 자동으로 들어간다.( dao바로 get해서 쓰면 됨)



질문이 있으시면 댓글로 질문을

도움이 되셨다면 공감 버튼을..!

Comments