Is there a way to extract the primary key (or ROWID) using NamedParameterJdbcTemplate and GeneratedKeyHolder?

I am trying to extract a ROWID or primary key using Spring NamedParameterJdbcTemplate and GeneratedKeyHolder.

I am trying to do something like this.

MapSqlParameterSource parameters = new MapSqlParameterSource()
                .addValue("param1", value1)
                .addValue("param2", value2);
KeyHolder keyHolder = new GeneratedKeyHolder();
namedParameterJdbcTemplate.update("INSERT INTO TABLE(ID, col1, col2)"
                + "VALUES(TABLE.TABLE_SEQ.NEXTVAL, :param1, :param2)",
                parameters, keyHolder);

After executing the above request, when I try to execute keyHolder.getKey().longValue(), it throws an exception below.

HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.DataRetrievalFailureException: The generated key is not of a supported numeric type. Unable to cast [oracle.sql.ROWID] to [java.lang.Number]

When I went through http://docs.oracle.com/cd/B28359_01/java.111/b31224/datacc.htm , I realized (I hope I did) that ojdbc does not map oracle RowId to java RowId.

Can anyone suggest a way to extract the key? (Yes, this can be done using PreparedStatement, but it makes my code a little ugly to read and manipulate some conditions). Your suggestions are greatly appreciated.

+5
2

namedParameterJdbcTemplate.update("INSERT INTO TABLE(ID, col1, col2)"
            + "VALUES(TABLE.TABLE_SEQ.NEXTVAL, :param1, :param2)",
            parameters, keyHolder, new String[]{"ID"});
+13

: , - Oracle , , "GENERATED_ID" ( )

       public Integer insertRecordReturnGeneratedId(final MyObject obj)
        {
        final String INSERT_QUERY = "INSERT INTO MY_TABLE  VALUES(GENERATED_ID_SEQ.NEXTVAL, :param1, :param2)";
        try
            {
                MapSqlParameterSource parameters = new MapSqlParameterSource().addValue( "param1", obj.getField1() ).addValue( "param2",  obj.getField1() ) ;
                final KeyHolder holder = new GeneratedKeyHolder();
                this.namedParameterJdbcTemplate.update( INSERT_QUERY, parameters, holder, new String[] {"GENERATED_ID" } );
                Number generatedId = holder.getKey();
               // Note: USING holder.getKey("GENERATED_ID") IS ok TOO.
                return generatedId.intValue();
            }
            catch( DataAccessException dataAccessException )
            {
    }
    }
0

All Articles