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

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

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

    Code Block
    int id = student.getId();

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

Code Block
languagexml
<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>
Code Block
languagejava
titleannotation
@Insert("INSERT INTO Students(id, name , email) VALUES  (#{id}, #{name}, #{email})")
@SelectKey(statement="select SEQ_IDSTUDENT.nextval FROM DUAL", keyProperty="id", before=true, resultType=int.class)
int insert(Student student);

...