Tobia
Tobia

Reputation: 9506

How to get inserted id using Spring Jdbctemplate.update(String sql, obj...args)

I'm using Jdbctemplate and I need the inserted id of a query. I read that I have to build a particular PreparedStatement and use GeneratedKeyHolder object.

The problem is that in my application all inserts method uses this JdbcTemplate update method:

getJdbcTemplate().update(SQL_INSERT,param1,param2,param3,...);

Is there another way to get the inserted id without refactoring all daos?

Upvotes: 12

Views: 29085

Answers (2)

alext
alext

Reputation: 802

This does not work for PostgreSQL, the holder returns all the attributes. Here is a link to the solution in PostgreSQL Spring: How to use KeyHolder with PostgreSQL

Upvotes: 0

Paulius Matulionis
Paulius Matulionis

Reputation: 23415

Looking at the documentation for NamedParameterJdbcTemplate and JdbcTemplate You have two choices:

use NamedParameterJdbcTemplate's update method.

use JdbcTemplate's update method.

There are also some other methods available which will populate the keys to the given GeneratedKeyHolder, it's up to you which one suits your needs.

EDIT

For e.g. using JdbcTemplate:

GeneratedKeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement statement = con.prepareStatement("INSERT INTO SOME_TABLE(NAME, VALUE) VALUES (?, ?) ", Statement.RETURN_GENERATED_KEYS);
        statement.setString(1, "SomeName");
        statement.setString(2, "SomeValue");
        return statement;
    }
}, holder);

long primaryKey = holder.getKey().longValue();

Upvotes: 25

Related Questions