通过 jdbctemplate 从 sql 插入身份

发布于 2024-08-09 14:00:52 字数 62 浏览 7 评论 0 原文

是否可以从 Spring jdbc 模板调用的 SQL 插入中获取 @@identity?如果是这样,怎么办?

Is it possible to get the @@identity from the SQL insert on a Spring jdbc template call? If so, how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

随风而去 2024-08-16 14:00:53

JDBCTemplate.update 方法已重载,以获取名为“GenerateKeyHolder”的对象,您可以使用该对象检索自动生成的密钥。例如(代码取自 此处):

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

The JDBCTemplate.update method is overloaded to take an object called a GeneratedKeyHolder which you can use to retrieve the autogenerated key. For example (code taken from here):

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
浊酒尽余欢 2024-08-16 14:00:53

SimpleJdbcInsert.executeAndReturnKey 怎么样?它有两种形式,具体取决于输入:

(1) 输入是一个 Map

public java.lang.NumberexecuteAndReturnKey(java.util.Mapargs)

从接口复制的描述:SimpleJdbcInsertOperations

使用传入的值执行插入并返回生成的键。
这需要指定具有自动生成键的列的名称。此方法将始终返回一个KeyHolder,但调用者必须验证它是否确实包含生成的密钥。

指定者:

executeAndReturnKey org/springframework/jdbc/core/simple/SimpleJdbcInsertOperations.html" rel="noreferrer">SimpleJdbcInsertOperations

参数:

args - 包含列名称和相应值的映射

退货:

生成的键值

(2)输入是一个SqlParameterSource

public java.lang.NumberexecuteAndReturnKey(SqlParameterSourceparameterSource)

从接口复制的描述:SimpleJdbcInsertOperations

使用传入的值执行插入并返回生成的键。
这需要指定具有自动生成键的列的名称。此方法将始终返回一个KeyHolder,但调用者必须验证它是否确实包含生成的密钥。

指定者:

executeAndReturnKey org/springframework/jdbc/core/simple/SimpleJdbcInsertOperations.html" rel="noreferrer">SimpleJdbcInsertOperations

参数:

parameterSource - SqlParameterSource 包含用于插入的值

退货:

生成的键值。

How about SimpleJdbcInsert.executeAndReturnKey? It takes two forms, depending on the input:

(1) The input is a Map

public java.lang.Number executeAndReturnKey(java.util.Map<java.lang.String,?> args)

Description copied from interface: SimpleJdbcInsertOperations

Execute the insert using the values passed in and return the generated key.
This requires that the name of the columns with auto generated keys have been specified. This method will always return a KeyHolder but the caller must verify that it actually contains the generated keys.

Specified by:

executeAndReturnKey in interface SimpleJdbcInsertOperations

Parameters:

args - Map containing column names and corresponding value

Returns:

the generated key value

(2) The input is a SqlParameterSource

public java.lang.Number executeAndReturnKey(SqlParameterSourceparameterSource)

Description copied from interface: SimpleJdbcInsertOperations

Execute the insert using the values passed in and return the generated key.
This requires that the name of the columns with auto generated keys have been specified. This method will always return a KeyHolder but the caller must verify that it actually contains the generated keys.

Specified by:

executeAndReturnKey in interface SimpleJdbcInsertOperations

Parameters:

parameterSource - SqlParameterSource containing values to use for insert

Returns:

the generated key value.

与他有关 2024-08-16 14:00:53

在 todd.pierzina 答案中添加详细注释/示例代码

jdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
        jdbcInsert.withTableName("TABLE_NAME").usingGeneratedKeyColumns(
                "Primary_key");
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("Column_NAME1", bean.getval1());
        parameters.put("Column_NAME2", bean.getval2());
        // execute insert
        Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(
                parameters));
           // convert Number to Int using ((Number) key).intValue()
            return ((Number) key).intValue();

Adding detailed notes/sample code to todd.pierzina answer

jdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
        jdbcInsert.withTableName("TABLE_NAME").usingGeneratedKeyColumns(
                "Primary_key");
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("Column_NAME1", bean.getval1());
        parameters.put("Column_NAME2", bean.getval2());
        // execute insert
        Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(
                parameters));
           // convert Number to Int using ((Number) key).intValue()
            return ((Number) key).intValue();
李不 2024-08-16 14:00:53

我不知道是否有“一行”,但这似乎可以解决问题(至少对于 MSSQL):

// -- call this after the insert query...
this._jdbcTemplate.queryForInt( "select @@identity" );

不错的文章 此处

I don't know if there is a "one-liner" but this seems to do the trick (for MSSQL at least):

// -- call this after the insert query...
this._jdbcTemplate.queryForInt( "select @@identity" );

Decent article here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文