이번포스팅은 테이블에 데이터 INSERT 후 시퀀스값 SELECT 해오는 것에 대하여 포스팅 하도록 하겠음
우선은 테스트 테이블을 생성 해보도록 하자
테이블명은 DBMS와 무관하게 동일하게 잡도록 해보겠음
테이블명 : seq_test
컬럼명 |
타입 |
idx |
bigint or number |
title |
varchar(20) |
MySQL 테이블 생성
CREATE TABLE seq_test(
idx bigint primary key auto_increment, title varchar(20) )
MS-SQL 테이블 생성
CREATE TABLE seq_test( idx bigint IDENTITY(1,1) primary key , title varchar(20) )
ORACLE 테이블 생성 (별도의 시퀀스 생성 필요)
CREATE TABLE seq_test( idx number primary key , title varchar(20) ); create sequence idx_test_seq start with 1 increment BY 1 maxvalue 10000;
테이블을 생성 하였다면 임의의 controller,dao,vo를 생성해보도록 하자
VO
public class Test { private int idx; private String title; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } }
CONTROLLER
@Autowired private Dao dao; @RequestMapping(value="/insertSelectSeq") public void insertSelectSeq(Test test) { try { test.setTitle("insert test"); System.out.println("등록전 idx 값 :"+test.getIdx()); dao.insertSelectSeq(test); System.out.println("등록후 idx 값 :"+test.getIdx()); } catch (Exception e) { e.printStackTrace(); } }
DAO
@Autowired private SqlSession sql; public int insertSelectSeq(Test test) throws SQLException { return sql.insert("sql.insertSelectSeq",test); }
위의 소스에서 보다시피 dao에서는 int 형으로 return을 주지만
컨트롤러에서는 별도로 받는 vo객체가 존재하지 않는다.
그냥 dao에 parameter로 넘겨준 test객체에 담기는 것이다.
DBMS별로 INSERT 후 시퀀스값을 SELECT 해오는방법중 본인은 2가지 방식을 설명
하도록 하겠음
1. MySQL, MS-SQL 처럼 시퀀스가 자동 증가인 DBMS일 경우
사용가능
<insert id="insertSelectSeq" parameterType="com..model.Test" useGeneratedKeys="true" keyProperty="idx"> INSERT INTO seq_test (title) VALUES(#{title}) </insert>
위 코드처럼 정해주면 된다
※ keyProperty는 vo에 정의해준 변수명이다.
(시퀀스 컬럼값과 일치 시켜줘야함)
그럼 위의 코드로 테스트를 해보도록 하자
본인은 MySQL로 진행을 해보도록 하겠음
실행결과
위의 결과처럼 INSERT 호출전 VO객체의 들어있던 idx 의 값은 0이었으나 INSERT 처리를 한 후에는
자동증가값이 들어가있는 것을 확인 하였다.
2. 오라클처럼 시퀀스를 별도록 등록해주어야 하는 경우
※ 해당 방법은 꼭 오라클이 아니고 MySQL,MS-SQL
모두 사용이 가능 한 방법이다
<!--oracle--> <insert id="insertSelectSeq" parameterType="com.model.Test"> INSERT INTO seq_test(idx,title) VALUES(idx_test_seq.nextval,#{title}) <selectKey keyProperty="idx" resultType="Integer" order="AFTER"> SELECT idx_test_seq.currval FROM dual </selectKey> </insert> <!--mysql--> <insert id="insertSelectSeq" parameterType="com.model.Test"> INSERT INTO seq_test(title) VALUES(#{title}) <selectKey keyProperty="idx" resultType="Integer" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey> </insert> <!--mssql--> <insert id="insertSelectSeq" parameterType="com.model.Test"> INSERT INTO seq_test(title) VALUES(#{title}) <selectKey keyProperty="idx" resultType="Integer" order="AFTER"> SELECT IDENT_CURRENT('seq_test') </selectKey> </insert>
DBMS 종류별로 각각의 Mybatis의 쿼리XML은 위와 같다.
※ MS-SQL 버전에서의 IDENT_CURRENT('seq_test') 의
seq_test는 insert했던 테이블 명을 적어주면 된다
그럼 위의 코드로 테스트를 해보도록 하자
본인은 오라클로 진행을 해보도록 하겠음
실행결과
위와같이 결과가 나왔다.
DBMS 무관하게 결과는 모두 동일하게 나올것이다.
1. 지속적인 구독을 원하신다면 네이버 이웃추가 부탁드립니다
2. 도움이 되셨다면 공감한번 꾹! 눌러주세요
3. 궁금하신점이 있으시다면 댓글 GOGO
ibatis vs mybatis LIKE절 검색하기 (0) | 2014.08.04 |
---|---|
ibatis vs mybatis 조건문 + mybatis 공백조건 비교시 안될경우 및 두개이상 조건주기 (0) | 2014.08.01 |
ibatis(iterate) vs mybatis(foreach) 비교 샘플 (0) | 2014.07.31 |