/
MyBatis 에서 insert 시 자동 생성키 사용하기

MyBatis 에서 insert 시 자동 생성키 사용하기

DBMS 가 자동 생성키를 지원할 경우(MySQL 의  mybatis 에서 사용하는 법 (마이바티스를 사용한 자바 퍼시스턴스 개발 에서 발췌)

table 구조
CREATE TABLE Students
(
  id INT(11) NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(50) NOT NULL,
  PRIMARY KEY (id)
);


  1. insert 구문의 속성중 하나인 useGeneratedKeys 를 true 로 설정한다.(기본값 false)

    <insert id="insertStudents" useGeneratedKeys="true"
        keyProperty="id">
      insert into Students (name ,email)
      values (#{name },#{email})
    </insert>
    annotation
    @Insert("INSERT INTO Students (NAME, EMAIL ) VALUES (#{name},#{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(Student st);
  2. 생성된 키는 다음 코드로 얻을 수 있다.

    int id = student.getId();

Oracle 은 AUTO INCREMENT 가 없으므로 SEQUENCE 를 사용해야 한다. 해당 시퀀스명이 SEQ_STUDENT 일때 다음과 같이 사용

<insert id="insertStudents">
  <selectKey keyProperty="id" resultType="int" order="BEFORE">
    select SEQ_ID.nextval FROM DUAL
  </selectKey>
  insert into Students
    (id, name , email)
  values
    (#{id}, #{name}, #{email})
</insert>
annotation
@Insert("INSERT INTO Students(id, name , email) VALUES  (#{id}, #{name}, #{email})")
@SelectKey(statement="select SEQ_STUDENT.nextval FROM DUAL", keyProperty="id", before=true, resultType=int.class)
int insert(Student student);



binding 되는 변수명이나 기타 다른 설정을 변경하려면 아래의 property 참고

<selectKey
  keyProperty="id"
  resultType="int"
  order="BEFORE"
  statementType="PREPARED">


Ref


Related content

MySQL 에서 외래 키 제약조건(Foreign Key Constraint) 끄고 작업하기
MySQL 에서 외래 키 제약조건(Foreign Key Constraint) 끄고 작업하기
More like this
DBMS 의 테이블과 컬럼 이름 최대 길이
DBMS 의 테이블과 컬럼 이름 최대 길이
More like this
command line 에서 빈 sqlite 데이터베이스 파일 만들기
command line 에서 빈 sqlite 데이터베이스 파일 만들기
More like this
MySQL 테이블 및 데이타베이스 이름 대소문자 구분 설정
MySQL 테이블 및 데이타베이스 이름 대소문자 구분 설정
More like this
MySQL database 와 table 의 character set encoding 확인하는 법
MySQL database 와 table 의 character set encoding 확인하는 법
More like this
redis 의 databases 갯수 확인 및 변경(SELECT INDEX)
redis 의 databases 갯수 확인 및 변경(SELECT INDEX)
More like this