Mybatis 쿼리 실행시 리턴값 바꾸기

less than 1 minute read

@Insert("INSERT INTO USERS (NAME,AGE) VALUES(#{name},#{age})") @SelectKey(statement="select STANDARDS_ID_SEQ.CURRVAL from dual", resultType = int.class, before = false, keyProperty = ID) @Options(useGeneratedKeys=true, keyProperty="ID", keyColumn="ID")

키값의 id리턴방법

 

xml방식

http://www.raistudies.com/mybatis/inserting-auto-generated-id-using-mybatis-return-id-to-java/

First of all, we have to change the schema of table Product to make the id field auto generated. Following is the DDL command to make the Product table with auto generated id:

1 CREATE TABLE Product(id BIGINT NOT NULL AUTO_INCREMENT , brand VARCHAR(20),
2 model VARCHAR(20), name VARCHAR(30) , PRIMARY KEY (id));

Here, I have used AUTO_INCREMENT to generate unique id in MySQL database.

Now, to use auto generated id in our mapping file ProductServices.xml to modify our command to use it:

view source

print?

1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
4
5 <mapper namespace="com.raistudies.services.ProductServices">
6
7     <insert id="save" parameterType="product" useGeneratedKeys="true" keyProperty="id"�  keyColumn="id">
8         INSERT INTO Product (brand,model,name)
9         VALUE (#{brand}, #{model}, #{name} )
10         <selectKey keyProperty="id" resultType="long" order="AFTER">
11             SELECT LAST_INSERT_ID();
12         </selectKey>
13     </insert>
14
15 </mapper>

Tags:

Updated: