우리 회사 프로젝트는 JPA 대신 Mybatis를 사용중이다.
전에 했던 프로젝트는 MSSQL에 프로시저 방식을 사용하였지만 이번 프로젝트에는 MySQL을 순수 쿼리로 사용하고 있다.
프로시저를 사용했을때, 프로시저에서 리턴해주는 output값을 어떻게 받아야할지 찾던 중
<select id="test" statementType="CALLABLE" parameterType="com.test.dto.RequestDto" resultType="Integer">
{
CALL TEST_PROCEDURE ( #{id}, #{password}, #{output, mode=OUT, jdbcType=INTEGER} )
}
</select>
이런식으로 RequestDto에 프로시저의 parameter 이외에 프로시저의 return 값까지 넣어주면 그 프로시저를 호출 하고 output 값이 담겨 온다.
이와 비슷한 방식으로 MySQL에 insert/update 쿼리를 수행 한 후 방금 실행된 row의 id값을 리턴받을 수 있다.
<insert id="test"
parameterType="com.test.dto.RequestDto"
useGeneratedKeys="true"
keyProperty="id">
INSERT INTO test_table (user_id, user_pw, create_time, update_time)
VALUES (#{userId}, #{userPw}, NOW(), NOW());
</insert>
사용법
useGeneratedKeys="true"
keyProperty="id"
@Getter
@Setter
@ToString
@Builder
public class RequestDto{
// return 받을 keyProperty변수
private Long id;
private String userId;
private String userPw;
}
useGeneratedKeys : (insert,update에 적용)자동생성 키값들을 사용하기 위해서 사용된다.
keyProperty : 리턴될 key property설정. 여러개를 사용한다면 ,(콤마)를 사용한다.
이렇게 사용하면 insert/update쿼리가 실행된 뒤 RequestDto에 id값에 수행되고 리턴된 id값이 들어가있는 것을 확인할 수 있다.