WEB/Mybatis

[mybatis/mariaDB] auto increment값 가져오기

Gh1324 2022. 3. 3. 14:44
728x90

데이터 베이스에 insert를 하다보면 PK를 시퀀스처럼 자동증가하는 값으로 설정하는 경우가 있을 것이다. 

그럴때 PK를 가져오고 싶은데 insert할때 값으로 넣지 않는 경우 가져올 수가 없다. 

그럴때 mybatis기능을 사용하면 된다.

 

 

sql문에 다음과 같은 속성을 넣어준다 .

 

useGeneratedKeys="true"

keyProperty="seq" 

<insert id="sample" parameterType="map" useGeneratedKeys="true" keyProperty="seq">
    INSERT INTO sample(test) VALUES (#{test});
</insert>
test = "me";
Map<String, Object> map = new HashMap<>();
map.put("test", test);
int result = sampleService.Sample(map);
String seq = map.get("seq").toString();

이렇게 하면 String seq에 자동증가하는 pk값을 받아올 수 있다. 

728x90