본문 바로가기
Database

[SQL] Insert 후 인덱스 값 가져오는법 (Mybatis&Ibatis)

by GoodDayDeveloper 2022. 7. 14.
반응형


insert한 다음 인덱스 값을 가져오는법을 정리해보겠습니다.
핵심포인트는 쿼리안에 selectKey로 데이터를 가져오는 것입니다.
여기서에서는 Mysql 기반으로 Mybatis와 Ibatis 두 종류를 정리해보았습니다.


우선 VO에 인덱스를 담을 객체를 생성합니다.
서버부분은 공통적인 부분이니 함께 다루겠습니다.

VO

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class VO {
 
  private int insertId = 0;
 
    
    public int getInsertId() {
        return insertId;
    }
 
    public void setInsertId(int insertId) {
        this.insertId = insertId;
    }
 
 
}
 
cs

저는 insertId라는 객체를 생성하였습니다.




Controller

 

1
2
int indexValue = insertAction(vo);
 
cs


보통 insert할때는 반환값이 없는 상태로 합니다만,
인덱스를 얻기 위해서 int형태의 객체를 생성해줍니다.
이대로 DAO까지 연결해준다음 XML을 통해서 Index값을 얻을 수 있습니다.




XML


이곳이 키포인트입니다.
쿼리를 사용하는 XML에서 Mybatis와 Ibatis에서 제공하는 selectKey를 이용하면
추가적인 데이터를 불러올 수 있습니다.


속성 keyProperty은 selectKey구문의 결과가 셋팅될 대상 프로퍼티입니다.
즉, vo에서 만들어준 insertId 객체를 가르킵니다.


그리고 resultClass / resultType을 integer 형태로 설정해줍니다.


그리고 쿼리에서는

  • Mybatis에서는 SELECT LAST_INSERT_ID()
  • Ibatis에서는 SELECT lastval

종류에 맞게 사용해주면 인덱스를 얻을 수 있습니다.



XML (Mybatis)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<insert id="insertAction" parameterType="VO">
    INSERT INTO table
    (
    code,
    content
    )
    VALUES
    (
    #{code},
    #{content}
    )
    
    <selectKey keyProperty="insertId" resultType="java.lang.Integer" >
         SELECT LAST_INSERT_ID()
  </selectKey>
</insert>
cs




XML (Ibatis)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<insert id="insertAction" parameterClass="VO">
    INSERT INTO table
    (
    code,
    content
    )
    VALUES
    (
    #{code},
    #{content}
    )
    
    <selectKey keyProperty="insertId" resultClass="java.lang.Integer" >
         SELECT lastval()
  </selectKey>
</insert>
cs



반응형

댓글