问题
Good day,
I have a table in db2, where the primary is_autoincrement
is set to Yes
. Means that everytime insert data to this table, no need to pass in the primary key value, because it will auto generate.
However, I need to get back the primary key value after insertion. The code is something as follow:
public integer insertRecord() {
//insertion sql code here
KeyHolder keyHolder = new GeneratedKeyHolder();
PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(
getInsertBatch2( ), new int[] {
java.sql.Types.TIMESTAMP, java.sql.Types.VARCHAR,
java.sql.Types.SMALLINT, java.sql.Types.DATE,
java.sql.Types.INTEGER } );
int updated = JdbcTemplate.update(
factory.newPreparedStatementCreator( params ), keyHolder);
log.trace("key value is " + keyHolder.getKey( );
//after insertion, return primary key
return id;
}
private String getInsertBatch2() {
StringBuilder sb = new StringBuilder( );
sb.append( "insert into " )
.append( getDefaultSchema( ) )
.append(
".batches( startdatetime, type, manual, processdate, originalbatchid) " );
sb.append( "values(?,?,?,?,?) " );
return sb.toString( );
}
The insertion query is something as follow:
insert into table1(startdatetime, type, manual, processdate, originalbatchid) value (-- all the value here -- );
When I try to print out the keyHolder, it is null.
Kindly advise how to get the primary key.
来源:https://stackoverflow.com/questions/24567633/get-back-the-primary-key-value-after-insertion-to-db2-table-by-keyholder