Share on Google+Share on Google+

SimpleJdbcInsert, Retrieving auto-generated keys

This section is about retrieving auto-generated keys using usingGeneratedKeyColumns" method of SimpleJdbcInsert.

SimpleJdbcInsert, Retrieving auto-generated keys

The auto-generated keys can be generated using "usingGeneratedKeyColumns" method. The name of the auto generated key column can be specified by passing it's name to method "usingGeneratedKeyColumns". The column must be integer or long and also it must be set for auto increment in database.

Example :

The main difference between simple insert and insert using "usingGeneratedKeyColumns" method is that you need not to add the 'id' to the Map. The "executeAndReturnKey" method returns a 'java.lang.Number' object whose numerical instance can be used in our domain class.

package net.roseindia;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class SJIautokey {
	private SimpleJdbcInsert insertRecord;

	public void setDataSource(DataSource dataSource) {
	new SimpleJdbcTemplate(dataSource);
	this.insertRecord = new SimpleJdbcInsert(dataSource).withTableName(

	public void add(Emp e) {
	Map parameters = new HashMap(3);
	parameters.put("firstname", e.getFirstName());
	parameters.put("lastname", e.getLastName());
	Number newId = insertRecord.executeAndReturnKey(parameters);

	public Emp newEmp() {
	Emp emp = new Emp();
	return emp;

package net.roseindia;

import org.springframework.beans.factory.xml.XmlBeanFactory;

public class SJIautokeyMain {

	public static void main(String[] args) {
	XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
	SJIautokey myBean = (SJIautokey) beanFactory.getBean("SJIautokey");


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
xmlns:xsi="" xmlns:context=""
<bean id="SJIautokey" class="net.roseindia.SJIautokey">
<property name="dataSource" ref="dataSource" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://" />
<property name="user" value="root" />
<property name="password" value="root" />

Output :

After executing code , the rows affected at database table "records" :

Download Source Code



Posted on: September 23, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null