I have a very simple MySql table with an auto increament primary key,
1 |
CREATE TABLE sampah |
2 |
( |
3 |
id INT (10) NOT NULL AUTO_INCREMENT, |
4 |
name VARCHAR (30), |
5 |
PRIMARY KEY (id) |
6 |
) |
my question is, how can i get my object’s generated primary key if i insert a new object to table “sampah”?
The answer is actually quite easy, as you can see here on my xml sql mapper, take a look an line 11.
01 |
<? xml version = "1.0" encoding = "UTF-8" ?> |
02 |
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > |
03 |
< mapper namespace = "com.edw.mybatis.mapper.SampahMapper" > |
04 |
05 |
< resultMap id = "SampahMap" type = "com.edw.mybatis.bean.Sampah" > |
06 |
< id column = "id" property = "id" jdbcType = "INTEGER" /> |
07 |
< result column = "name" property = "name" jdbcType = "VARCHAR" /> |
08 |
</ resultMap > |
09 |
10 |
< insert id = "saveUsingXML" parameterType = "com.edw.mybatis.bean.Sampah" |
11 |
useGeneratedKeys = "true" keyProperty = "id" > |
12 |
insert into sampah(name) |
13 |
values (#{name,jdbcType=VARCHAR}) |
14 |
</ insert > |
15 |
16 |
</ mapper > |
Here is my main java class, you can see how i got my generated id in line 25.
01 |
package com.edw.mybatis.main; |
02 |
03 |
import com.edw.mybatis.bean.Sampah; |
04 |
import com.edw.mybatis.config.MyBatisSqlSessionFactory; |
05 |
import com.edw.mybatis.mapper.SampahMapper; |
06 |
import org.apache.ibatis.session.SqlSession; |
07 |
import org.apache.log4j.Logger; |
08 |
09 |
public class Main { |
10 |
11 |
private Logger logger = Logger.getLogger(Main. class ); |
12 |
13 |
public Main() { |
14 |
} |
15 |
16 |
private void testSampah() { |
17 |
SqlSession session = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession(); |
18 |
try { |
19 |
SampahMapper sampahMapper = session.getMapper(SampahMapper. class ); |
20 |
Sampah sampah1 = new Sampah(); |
21 |
sampah1.setName( "satu satu" ); |
22 |
sampahMapper.saveUsingXML(sampah1); |
23 |
24 |
// my generated ID |
25 |
logger.debug(sampah1.getId()); |
26 |
27 |
session.commit(); |
28 |
} finally { |
29 |
session.close(); |
30 |
} |
31 |
} |
32 |
33 |
public static void main(String[] args) { |
34 |
Main main = new Main(); |
35 |
main.testSampah(); |
36 |
} |
37 |
} |
Easy isnt it?