Generated Keys

Basic Java
≈ 2 min read

Sometimes the database creates part of a new row itself

When inserting a record, the application may not know its future identifier. For example, the id value may be generated by a sequence or an identity mechanism in the database. After the INSERT, that key is often needed immediately: to return it to the client or use it in the next related record.

Ask JDBC to return generated values

String sql = "INSERT INTO users(name) VALUES (?)";

try (PreparedStatement statement = connection.prepareStatement(
        sql, Statement.RETURN_GENERATED_KEYS)) {

    statement.setString(1, "Mila");
    statement.executeUpdate();

    try (ResultSet keys = statement.getGeneratedKeys()) {
        if (keys.next()) {
            long id = keys.getLong(1);
            System.out.println(id);
        }
    }
}

The Statement.RETURN_GENERATED_KEYS flag tells the driver that values generated by the database will be needed after execution. Then getGeneratedKeys() returns them as an ordinary ResultSet.

The exact result depends on the database and driver

JDBC defines the API for retrieving keys, but the mechanism that generates them belongs to the specific DBMS. So you should not assume that every command and every driver will return the same set of values. If the application requires particular columns, take the capabilities of the selected database and driver into account.

Do not run a separate SELECT just to find the id of the row you inserted. If the database and driver support generated keys, obtaining the key from the same INSERT is usually more precise and simpler.