selectKey option
사용: mybatis에서 insert나 update 쿼리를 실행한 후, 결과를 바로 가져와야 할 경우
예) 도메인 객체
1
2
3
4
5
6
|
public Student {
int id; //아이디
String name; //이름
String email; //이메일
Date regist_date; //등록일
}
| cs |
예) controller
1
2
3
4
5
6
|
Student student = new Student();
student.setName('bla');
student.setEmail('bla@naver.com');
mapper.insertStudents(student); // 쿼리 실행
student.getId(); // 추출 가능
| cs |
1) 자동 생성키를 지원하는 경우: mysql ...
- useGenerateKey, keyProperty option 사용
1
2
3
4
|
<insert id="insertStudents" useGeneratedKeys="true"
keyProperty="id" parameterType="Student">
insert into Students ( name, email )
values ( #{name}, #{email} )
</insert>
| cs |
2) 자동 생성키를 지원하지 않는 경우: oracle
- selectKey option 사용
- oracle의 경우 auto increment가 없고 sequence를 사용해야하기 때문에 1)의 옵션 사용 불가능
1
2
3
4
5
6
7
8
9
|
<insert id="insertStudents" parameterType="Student">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select SEQ_ID.nexyval FROM DUAL
</selectKey>
insert into Students
(id, name , email)
values
(#{id}, #{name}, #{email})
</insert>
| cs |