728x90
Board라는 게시판에서 입력을 수행시 boardID값을 기존에 최대값에 +1한 다음에
그 값을 입력하고 싶다면 아래의 같이 처리하면 된다.
<insert id="insertBoard" parameterType="Board">
<selectKey resultType="string" keyProperty="boardID" order="BEFORE">
SELECT MAX(boardID)+1 FROM board
</selectKey>
INSERT INTO board(boardID, title, content)
VALUES(#{boardID}, #{title}, #{content})
</insert>
gps 값에 +1 한값을 insert
<insert id="childReplyInsert" parameterType="boardReplyConfig" >
<selectKey resultType="int" keyProperty="grps" order="BEFORE">
select max(grps)+1 from board_reply where bno = #{bno} and grp = #{grp}
</selectKey>
insert into board_reply (bno, grp, grpl, grps, writer, content , wdate)
values (#{bno} , #{grp} , 1 , #{grps} , #{writer} , #{content} , now() )
</insert>
방금insert한 테이블의 auto_increment로 증가된 컬럼값을 가져오는 쿼리이다.
parameter 타입이 DTO , Map의 종류인 경우,
last insert key 값의 경우 자동으로 파라메터로 넣어준 맵 , dto 에 세팅된다.
public int parentReplyInsert(BoardReplyDTO boardReplyDTO) {
SqlSession session = getSqlSessionFactory().openSession();
int rowCount = session.insert("parentReplyInert", boardReplyDTO);
int no = Integer.parseInt(boardReplyDTO.getNo());
int key = session.update("parentReplyCheck", no);
session.close();
return key;
}
<insert id="parentReplyInert" parameterType="boardReplyConfig" useGeneratedKeys="true" keyProperty="no" >
insert into board_reply (bno, grp, grpl, grps, writer, content , wdate)
values ( #{bno} , 0 , 0 , 0 , #{writer} , #{content} , now() )
<selectKey resultType="String" keyProperty="no" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
<update id="parentReplyCheck" parameterType="int" >
update board_reply set grp = #{no} where no = #{no}
</update>
이처럼 selectKey를 사용하려면 applicationContext.xml에서 아래처럼 BATCH 기본설정부분이
주석처리되거나 없어야 한다
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<!--<constructor-arg index="1" value="BATCH" /> -->
</bean>
728x90