Instead, use ResultSet#getLong() . If in vain, try ResultSet#getRowId() and finally drop it at oracle.sql.ROWID . If the returned hex string is actually a hex identifier, you can try converting it to decimal using Long#valueOf() or Integer#valueOf() .
Long id = Long.valueOf(hexId, 16);
However, the Oracle JDBC driver has not supported ResultSet#getGeneratedKeys() for a long time and is still somewhat troublesome with it. If you cannot get this right, you need to execute SELECT CURRVAL(sequencename) in the same statement as in insert , or in a new expression inside the same transaction if it was PreparedStatement . Basic example:
public void create(User user) throws SQLException { Connection connection = null; PreparedStatement preparedStatement = null; Statement statement = null; ResultSet generatedKeys = null; try { connection = daoFactory.getConnection(); preparedStatement = connection.prepareStatement(SQL_INSERT); preparedStatement.setValue(1, user.getName()); // Set more values here. int affectedRows = preparedStatement.executeUpdate(); if (affectedRows == 0) { throw new SQLException("Creating user failed, no rows affected."); } statement = connection.createStatement(); generatedKeys = statement.executeQuery(SQL_CURRVAL); if (generatedKeys.next()) { user.setId(generatedKeys.getLong(1)); } else { throw new SQLException("Creating user failed, no generated key obtained."); } } finally { close(generatedKeys); close(statement); close(preparedStatement); close(connection); } }
Oh, from your code example, the next line
stmt.RETURN_GENERATED_KEYS;
completely redundant. Take it away.
You can find here another example, which I published earlier about receiving generated keys, it uses the usual getGeneratedKeys() approach.
BalusC Dec 29 '09 at 20:24 2009-12-29 20:24
source share