I have a very simple MySql table with an auto increament primary key,
3 |
id INT(10) NOT NULL AUTO_INCREMENT, |
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" > |
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" /> |
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}) |
Here is my main java class, you can see how i got my generated id in line 25.
01 |
package com.edw.mybatis.main; |
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; |
11 |
private Logger logger = Logger.getLogger(Main.class); |
16 |
private void testSampah() { |
17 |
SqlSession session = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession(); |
19 |
SampahMapper sampahMapper = session.getMapper(SampahMapper.class); |
20 |
Sampah sampah1 = new Sampah(); |
21 |
sampah1.setName("satu satu"); |
22 |
sampahMapper.saveUsingXML(sampah1); |
25 |
logger.debug(sampah1.getId()); |
33 |
public static void main(String[] args) { |
34 |
Main main = new Main(); |
Easy isnt it? 