Brian Roach 接受的答案是正确的。我正在添加一些想法和一个带有完整代码的示例。
RETURN_GENERATED_KEYS
并不意味着“返回生成的密钥”</h1
>
原来的海报似乎被国旗的措辞弄糊涂了,这是可以理解的Statement.RETURN_GENERATED_KEYS
。与直觉相反,传递此标志不会改变方法的行为PreparedStatement::executeUpdate
。该方法总是返回一个int
,即受执行的 SQL 影响的行数。“executeUpdate”方法从不返回生成的密钥。
int countRowsAffected = pstmt.executeUpdate(); // Always return number of rows affected, *not* the generated keys.
问,你就会收到
如果您想要生成的密钥,您必须执行两个步骤:
- 传递旗帜,然后
- 请求
ResultSet
由仅包含生成的键值的行组成。
这种安排允许您添加取回生成的键的行为,同时保持其他所需的行为,计算受影响的行数。
示例代码
这是一个几乎真实的示例,取自 Java 8 应用程序,该应用程序从数据馈送中抓取数据。我认为在这种情况下,一个完整的例子可能比一个最小的例子更有用。
次要细节……这段代码在语法或其他方面可能并不完美,因为我复制粘贴修改过的真实源代码。我使用UUID 数据类型而不是整数作为表的代理主键。这些课程是我自己的CharHelper
,DBHelper
这里的细节并不重要。x
和y
变量是我自己的应用程序有意义的数据的替代品。我的日志调用是对SLF4J框架进行的。UUID 十六进制字符串是将日志中的报告链接回原始源代码的便捷方式。数据库是Postgres,但这种代码应该适用于任何支持生成密钥报告的数据库。
public UUID dbWrite ( String x , String y , DateTime whenRetrievedArg ) {
if ( whenRetrievedArg == null ) {
logger.error( "Passed null for whenRetrievedArg. Message # 2112ed1a-4612-4d5d-8cc5-bf27087a350d." );
return null;
}
Boolean rowInsertComplete = Boolean.FALSE; // Might be used for debugging or logging or some logic in other copy-pasted methods.
String method = "Method 'dbWrite'";
String message = "Insert row for some_table_ in " + method + ". Message # edbea872-d3ed-489c-94e8-106a8e3b58f7.";
this.logger.trace( message );
String tableName = "some_table_";
java.sql.Timestamp tsWhenRetrieved = new java.sql.Timestamp( whenRetrievedArg.getMillis() ); // Convert Joda-Time DatTime object to a java.sql.Timestamp object.
UUID uuidNew = null;
StringBuilder sql = new StringBuilder( AbstractPersister.INITIAL_CAPACITY_OF_SQL_STRING ); // private final static Integer INITIAL_CAPACITY_OF_SQL_STRING = 1024;
sql.append( "INSERT INTO " ).append( tableName ).append( CharHelper.CHAR.PAREN_OPEN_SPACED ).append( " x_ , y_ " ).append( CharHelper.CHAR.PAREN_CLOSED ).append( DBHelper.SQL_NEWLINE );
sql.append( "VALUES ( ? , ? , ? ) " ).append( DBHelper.SQL_NEWLINE );
sql.append( ";" );
try ( Connection conn = DBHelper.instance().dataSource().getConnection() ;
在这里,我们执行第 1 步,传递RETURN_GENERATED_KEYS
标志。
PreparedStatement pstmt = conn.prepareStatement( sql.toString() , Statement.RETURN_GENERATED_KEYS ); ) {
我们继续准备和执行语句。请注意,int countRows = pstmt.executeUpdate();
返回受影响行的计数,而不是生成的键。
pstmt.setString( 1 , x );
pstmt.setString( 2 , y );
pstmt.setTimestamp( 3 , tsWhenRetrieved );
// Execute
int countRows = pstmt.executeUpdate(); // Always returns an int, a count of affected rows. Does *not* return the generated keys.
if ( countRows == 0 ) { // Bad.
this.logger.error( "Insert into database for new " + tableName + " failed to affect any rows. Message # 67e8de7e-67a5-42a6-a4fc-06929211e6e3." );
} else if ( countRows == 1 ) { // Good.
rowInsertComplete = Boolean.TRUE;
} else if ( countRows > 1 ) { // Bad.
rowInsertComplete = Boolean.TRUE;
this.logger.error( "Insert into database for new " + tableName + " failed, affecting more than one row. Should not be possible. Message # a366e215-6cf2-4e5c-8443-0b5d537cbd68." );
} else { // Impossible.
this.logger.error( "Should never reach this Case-Else with countRows value " + countRows + " Message # 48af80d4-6f50-4c52-8ea8-98856873f3bb." );
}
在这里,我们执行第 2 步,请求生成密钥的 ResultSet。在此示例中,我们插入了一行并期望返回一个生成的密钥。
if ( rowInsertComplete ) {
// Return new row’s primary key value.
ResultSet genKeys = pstmt.getGeneratedKeys();
if ( genKeys.next() ) {
uuidNew = ( UUID ) genKeys.getObject( 1 ); // ResultSet should have exactly one column, the primary key of INSERT table.
} else {
logger.error( "Failed to get a generated key returned from database INSERT. Message # 6426843e-30b6-4237-b110-ec93faf7537d." );
}
}
剩下的就是错误处理和清理。请注意,我们在此代码的底部返回 UUID ,即插入记录的生成主键。
} catch ( SQLException ex ) {
// We expect to have occasional violations of unique constraint on this table in this data-scraping app.
String sqlState = ex.getSQLState();
if ( sqlState.equals( DBHelper.SQL_STATE.POSTGRES.UNIQUE_CONSTRAINT_VIOLATION ) ) { // SqlState code '23505' = 'unique_violation'.
this.logger.trace( "Found existing row when inserting a '" + tableName + "' row for y: " + y + ". Expected to happen on most attempts. Message # 0131e8aa-0bf6-4d19-b1b3-2ed9d333df27." );
return null; // Bail out.
} else { // Else any other exception, throw it.
this.logger.error( "SQLException during: " + method + " for table: " + tableName + ", for y: " + y + ". Message # 67908d00-2a5f-4e4e-815c-5e5a480d614b.\n" + ex );
return null; // Bail out.
}
} catch ( Exception ex ) {
this.logger.error( "Exception during: " + method + " for table: " + tableName + ", for y: " + y + ". Message # eecc25d8-de38-458a-bb46-bd6f33117969.\n" + ex );
return null; // Bail out.
}
if ( uuidNew == null ) {
logger.error( "Returning a null uuidNew var. SQL: {} \nMessage # 92e2374b-8095-4557-a4ed-291652c210ae." , sql );
}
return uuidNew;
}