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

こ雲淡風輕ζ 提交于 2019-12-05 11:12:56

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!