Home  >  Spring Core

How to Get Auto Generated ID in Spring JDBC| Spring KeyHolder Example

By Arvind Rai, November 07, 2013
For a programmer getting auto generated id of a newly inserted row in table is a little bit tricky. In this page we will learn how the spring provides an easy way to get that. Spring provides KeyHolder which helps to get auto generated key. KeyHolder is supported by JDBC 3.0.

FarmarDao.java
package com.concretepage.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
@Repository
public class FarmarDao {
	private JdbcTemplate jdbcTemplate;
    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
    public long setName(final String name){
    	final String sql = "insert into farmar (name) values(?)";
    	KeyHolder keyHolder = new GeneratedKeyHolder();
    	jdbcTemplate.update(
    	    new PreparedStatementCreator() {
    	        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
    	            PreparedStatement pst =
    	                con.prepareStatement(sql, new String[] {"id"});
    	            pst.setString(1, name);
    	            return pst;
    	        }
    	    },
    	    keyHolder);
    	return (Long)keyHolder.getKey();
    }
}
 



JdbcTemplate.update needs the object of PreparedStatementCreator and KeyHolder. Here KeyHolder object has been created by GeneratedKeyHolder. And finally keyHolder.getKey() is returning the required id.

SpringTest.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.concretepage.dao.FarmarDao;
public class SpringTest {
	public static void main(String[] args) {
		ApplicationContext  context = new ClassPathXmlApplicationContext("spring.xml");
		FarmarDao farmar = (FarmarDao)context.getBean("farmarDao");
		long id = farmar.setName("Ram");
		System.out.println("Index is: "+id);
	}
}   
 
Table Schema
CREATE TABLE `farmar` (
	`id` INT(10) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`id`)
)
Download Source Code for Complete Example
how-to-get-auto-generated-id-in-spring-jdbc.zip
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us