320x100
sequence값을 조회한 후 insert하는 방법을 정리해 보았다.
1 - Sequence 값 VO에 세팅하는 방법
SELECT 한 시퀀스값을 vo에 세팅해준다.
<select id="selectSeq" resultType="java.lang.String">
SELECT NEXTVAL(sq_sample_seq) FROM DUAL
</select>
<insert id="insert1" parameterType="com.test.sample.vo.SamplePVO">
INSERT INTO TBL_SAMPLE
(
SAMPLE_SEQ,
SAMPLE_ID
)
VALUES
(
#{sampleSeq}
, #{sampleId}
)
</insert>
// 시퀀스 조회
String sampleSeq = sampleService.selectSeq();
// vo 생성
SamplePVO pvo = new SamplePVO();
// vo 세팅
pvo.setSampleId("sampleId");
pvo.setSampleSeq(sampleSeq);
// insert
sampleService.insert1(pvo);
2 - selectKey 이용하기
<insert id="insert2" parameterType="com.test.sample.vo.SamplePVO">
<selectKey keyProperty="sampleSeq" resultType="java.lang.String" order="BEFORE">
SELECT NEXTVAL(sq_sample_seq) FROM DUAL
</selectKey>
INSERT INTO TBL_SAMPLE
(
SAMPLE_SEQ,
SAMPLE_ID
)
VALUES
(
#{sampleSeq}
, #{sampleId}
)
</insert>
order 는 INSERT 문을 실행하기 전에 할거냐 한후에 할거냐 결정해주는 것인데 before 이므로 쿼리문 실행전이다.
after로 하게되면 쿼리문을 실행후 해당 쿼리를 실행한다.
keyProperty에 변수명을 입력해준다.
1번보단 간결하다.
+) 주의할 점은 selectKey를 이용할 때 Mapping된 java 함수의 리턴 값을 void로 설정하는 것이다.
3 - SEQUENCE.nextVAL을 바로 사용하기
<insert id="insert3" parameterType="com.test.sample.vo.SamplePVO">
INSERT INTO TBL_SAMPLE
(
SAMPLE_SEQ,
SAMPLE_ID
)
VALUES
(
sq_sample_seq.NEXTVAL,
, #{sampleId}
)
</insert>
selectKey 해주지 않고도 바로 NEXTVAL 을 사용함으로써
훨씬 코드가 간결해졌다.
회사에서는 사람들이 3가지 방법을 모두 사용하고 있는데,
어떤 방법이 제일 효율적인지는 좀 더 찾아봐야겠다.
제일 간결한건 3번인듯 하다.
320x100
'DB' 카테고리의 다른 글
[mysql] 사용자 정의 변수 사용하기 (0) | 2023.12.04 |
---|---|
[mysql] sysdate(), now(), current_timestamp() 차이 (2) | 2023.11.29 |
[MariaDB] sysdate() VS now() (0) | 2023.06.05 |