Get back the primary key value after insertion to db2 table by KeyHolder

穿精又带淫゛_ 提交于 2019-12-04 05:35:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!