SQL/Mybatis Framework
마지막에 추가한 데이터의 index 가져오는 방법
지구
2018. 7. 19. 12:33
마지막 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 필드에 바로 매칭시켜줌! )
반응형