在使用Spring JDBCTemplate在数据库中插入新的数据记录后,如何获取生成的ID? [英] How to get generated ID after I inserted into a new data record in database using Spring JDBCTemplate?
问题描述
当我使用Spring JDBCTemplate时,我遇到了一个非常常见的问题,我想在将新的数据记录插入数据库后获取ID值,此ID值将引用另一个相关表。我尝试下面的方式来插入它,但我总是返回1而不是其真正的唯一ID。 (我使用MySQL作为数据库)
I got a very common question when I was using Spring JDBCTemplate, I want to get the ID value after I inserted a new data record into database, this ID value will be referred to another related table. I tried the following way to insert it, but I always return 1 rather than its real unique ID. (I use MySQL as the database)
public int insert(BasicModel entity) {
String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);
log.info("SQL Statement for inserting into: " + insertIntoSql);
return this.jdbcTemplate.update(insertIntoSql);
}
推荐答案
受影响的行数
the number of rows affected
INSERT
语句总是 1
不同的数据库以不同的方式支持生成的密钥提取,但是大多数JDBC驱动程序抽象这一点,并且 JdbcTemplate
支持这一点。引用 12.2.8检索自动生成的键
Which is always 1
for INSERT
statement. Different databases support generated key extraction in different ways, but most JDBC drivers abstract this and JdbcTemplate
supports this. Quoting 12.2.8 Retrieving auto-generated keys
update()
检索由数据库生成的主键。这种支持是JDBC 3.0标准的一部分;有关详细信息,请参阅规范的第13.6章。
An
update()
convenience method supports the retrieval of primary keys generated by the database. This support is part of the JDBC 3.0 standard; see Chapter 13.6 of the specification for details.
基本上你需要这个更详细的语句:
Basically you need this much more verbose statement:
final String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
return connection.prepareStatement(insertIntoSql, new String[] {"id"});
}
}, keyHolder);
return keyHolder.getKey().intValue();
这篇关于在使用Spring JDBCTemplate在数据库中插入新的数据记录后,如何获取生成的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!