如何使用Spring Jdbctemplate.update(String sql,obj ... args)获取插入的ID [英] How to get inserted id using Spring Jdbctemplate.update(String sql, obj...args)

查看:290
本文介绍了如何使用Spring Jdbctemplate.update(String sql,obj ... args)获取插入的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jdbctemplate,并且需要插入查询的ID. 我读到我必须构建一个特定的PreparedStatement并使用GeneratedKeyHolder对象.

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.

问题在于,在我的应用程序中,所有inserts方法都使用此JdbcTemplate更新方法:

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

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

还有另一种方法来获取插入的ID,而无需重构所有的dao吗?

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

推荐答案

查看使用NamedParameterJdbcTemplate使用JdbcTemplate还有其他一些可用方法,这些方法将填充给定

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.

编辑

例如使用JdbcTemplate:

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();

这篇关于如何使用Spring Jdbctemplate.update(String sql,obj ... args)获取插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆