Why don t you make use of Oracle s sequence
facility? You can t do anything better/safer using Java.
Edit: Your main concern is thus database performance. You didn t want to connect "again" to get the generated ID from the database. This concern is not needed if you just make use of connection pooling and just reuse the same connection to obtain the generated key immediately. Most JDBC drivers can give you the generated key back by Statement#getGeneratedKeys()
. The newer JDBC drivers of Oracle supports it.
Here s a basic example:
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet generatedKeys = null;
try {
connection = database.getConnection();
preparedStatement = connection.prepareStatement("INSERT INTO user (name, age) VALUES (?, ?)";
preparedStatement.setString(user.getName());
preparedStatement.setInteger(user.getAge());
int affectedRows = preparedStatement.executeUpdate();
if (affectedRows == 0) {
throw new DAOException("Creating user failed, no rows affected.");
}
generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
user.setId(generatedKeys.getLong(1)); // Here s the magic.
} else {
throw new DAOException("Creating user failed, no generated key obtained.");
}
} catch (SQLException e) {
throw new DAOException(e);
} finally {
close(connection, preparedStatement, generatedKeys);
}