Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the autoincremented id when I insert a record in a table via jdbctemplate

private void insertIntoMyTable (Myclass m) {
    String query = "INSERT INTO MYTABLE (NAME) VALUES (?)";
    jdbcTemplate.update(query, m.getName());
}

When the above query inserts a record, the ID column in the table autoincrements.

Is there a way to get this auto incremented ID back at the time of the insertion. So in this example the return value of my method would be int

like image 559
birdy Avatar asked Oct 14 '12 13:10

birdy


People also ask

How to get auto-Generated Key with JdbcTemplate?

To retrieve auto-generated primery keys generated by database using JdbcTemplate, update() with PreparedStatementCreator is a convenient method. Provide PreparedStatementCreator as first argument and KeyHolder as second argument. KeyHolder holds the generated primary key, getKey() returns the value.

What is the return value of JdbcTemplate update?

JdbcTemplate. update() returns number of rows affected - so you not only know that delete/update was sucessfull, you also know how many rows were deleted/updated.

How do I use Sqlparametersource?

Method SummaryDetermine the SQL type for the specified named parameter. Determine the type name for the specified named parameter. Return the parameter value for the requested named parameter. Determine whether there is a value for the specified named parameter.

What is SimpleJdbcInsert?

A SimpleJdbcInsert is a multithreaded, reusable object providing easy insert capabilities for a table. It provides meta-data processing to simplify the code needed to construct a basic insert statement. All you need to provide is the name of the table and a Map containing the column names and the column values.


2 Answers

Check this reference. You can use jdbcTemplate.update as:

EDIT Added imports as asked

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

following is the code usage:

final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
    new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps =
                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
            ps.setString(1, name);
            return ps;
        }
    },
    keyHolder);
// keyHolder.getKey() now contains the generated key
like image 63
Anshu Avatar answered Oct 17 '22 02:10

Anshu


I get id generated by database (MSSQL) after insert like below, imports:

  import org.springframework.jdbc.core.BeanPropertyRowMapper;
  import org.springframework.jdbc.core.JdbcTemplate;
  import org.springframework.jdbc.core.RowMapper;
  import org.springframework.jdbc.core.SqlParameter;
  import org.springframework.jdbc.core.SqlReturnResultSet;
  import org.springframework.jdbc.core.simple.SimpleJdbcCall;

and the code snippet:

    final String INSERT_SQL = "INSERT INTO [table]\n"
            + " ([column_1]\n"
            + " ,[column_2])\n"
            + " VALUES\n" +
            " (?, ?)";

    Connection connection = jdbcTemplate.getDataSource().getConnection();
    PreparedStatement preparedStatement = connection.prepareStatement(INSERT_INVOICE_SQL, Statement.RETURN_GENERATED_KEYS);
    preparedStatement.setString(1, "test 1");
    preparedStatement.setString(2, "test 2");

    preparedStatement.executeUpdate();
    ResultSet keys = preparedStatement.getGeneratedKeys();

    if (keys.next()) {
        Integer generatedId = keys.getInt(1); //id returned after insert execution
    } 
like image 42
m.a.tomsik Avatar answered Oct 17 '22 04:10

m.a.tomsik