마지막 insert 한 row의 index 가져오는 방법
메인프로젝트를 진행하면서 방금 추가한 댓글의 고유넘버를 가져와야 할 때 되게 간편하고 효과적이었다.
* MyBatis 의 버전이 2.x 버전에서 3.x 버전으로 변경되면서 사용하는 방법이 다르니 참고
* MySQL 과 MyBatis 사용 참고
1. 2.x 버전 => <selectKey> 태그와 keyProperty 활용
1 2 3 4 5 6 7 8 9 | <insert id="insertComment" parameterType="comment"> <selectKey resultType="int" keyProperty="comment_no" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO COMMENT (user_id, board_no, comm_time, comm_content) VALUES ( #{user.userId}, #{boardNo}, NOW(), #{commentContent} ) </insert> | cs |
3. 3.x 버전 => useGeneratedKeys 와 keyProperty 활용
1 2 3 4 5 | <insert id="insertComment" parameterType="comment" useGeneratedKeys="true" keyProperty="commentNo"> INSERT INTO COMMENT (user_id, board_no, comm_time, comm_content) VALUES ( #{user.userId}, #{boardNo}, NOW(), #{commentContent} ) </insert> | cs |
처음에 몰랐을 때는 3.x 버전을 사용하면서 2.x 버전을 사용하다보니 계속 1이 리턴되어 헤멨었다.
사용하다보니 3.x 버전이 훨 편한 것 같다. (comment VO 객체에 있는 commentNo 필드에 바로 매칭시켜줌! )
반응형
'SQL > Mybatis Framework' 카테고리의 다른 글
[Mybatis] entity mapping to camel case (0) | 2021.07.13 |
---|---|
[Mybatis] update 문 parametertype 을 map 으로 받아 foreach 처리하는 방법 (0) | 2020.05.18 |
[MyBatis] PK가 없으면 INSERT, 있으면 UPDATE -> LIST 로 처리하기 (0) | 2020.04.02 |
[MyBatis] #{} 와 ${} 의 차이 (0) | 2020.04.02 |
[MyBatis] SqlSessionFactoryBean 속성 정리 (0) | 2020.01.08 |
댓글