반응형
SMALL
하기
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)
);
SQL
Copy
SQL
- insert 구문의 속성중 하나인 useGeneratedKeys 를 true 로 설정한다.(기본값 false)
annotation
@Insert("INSERT INTO Students (NAME, EMAIL ) VALUES (#{name},#{email})") @Options(useGeneratedKeys = true, keyProperty = "id") void insert(Student st);
JavaCopyJAVA -
<insert id="insertStudents" useGeneratedKeys="true" keyProperty="id"> insert into Students (name ,email) values (#{name },#{email}) </insert>
XMLCopyXML - 생성된 키는 다음 코드로 얻을 수 있다.
-
int id = student.getId();
Plain textCopyCODE
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>
XML
Copy
XML
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);
Java
Copy
JAVA
binding 되는 변수명이나 기타 다른 설정을 변경하려면 아래의 property 참고
<selectKey
keyProperty="id"
resultType="int"
order="BEFORE"
statementType="PREPARED">
Plain text
Copy
CODE
Ref
![](https://blog.kakaocdn.net/dn/bBbWvv/btsgGiKd3ZJ/ZspmZ9eqpwfGPyACS4J490/img.jpg)
- http://www.mybatis.org/generator/configreference/generatedKey.html
- http://mybatis.github.io/mybatis-3/ko/sqlmap-xml.html
반응형
LIST
'Programming > MyBatis' 카테고리의 다른 글
MYBATIS INSERT 쿼리 자동생성 - 오라클 (0) | 2025.01.19 |
---|---|
MYBATIS INSERT 쿼리 자동생성 - 오라클 (0) | 2023.05.20 |