What is Context and Generated Keys?

Asked

Viewed 185 times

3

I’d like to know what exactly context class connection (I’ve seen methods in relation to this like getConnectionFromContext, or something like that) and Generated Keys as the Preparedstatment constant: PreparedStatment.RETURN_GERENERATE_KEYS

  • 1

    getConnectionFromContext? Where did you see this? Can you include it to see what context this is? A JNDI context? Include more details about this context to help you, the other part is quiet ;)

1 answer

2

Since you have not included more details about what this context is I will not assume that it is a context of JNDI, a Spring, CDI, or any other context. So just include answer to the second question :)

Generated Keys are attributes automatically generated by DBMS, such as Row id, Identities, values generated by triggers, etc. In JDBC, starting with version 3, you can explicitly inform statement whether or not such values are returned in a ResultSet.

The constant PreparedStatement.RETURN_GENERATED_KEYS is used to indicate which auto values generated by DBMS should be returned after the execution of statement. Say you have the following table (using Postgresql as an example):

CREATE TABLE pessoas
(
  id serial NOT NULL,
  nome character varying(300),
  CONSTRAINT pessoa_id_pk PRIMARY KEY (id)
);

We say that the id be the type serial, that will generate a sequence and will be auto generated by Postgresql. To simulate the recovery of this value we can do something like this:

final String sql = "INSERT INTO pessoas(nome) VALUES (?);";
final Connection conn = this.getConnection(); // recupera a conexão de alguma forma
try (final PreparedStatement ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
    ps.setString(1, "Bruno");
    ps.execute();
    try (final ResultSet rs = ps.getGeneratedKeys()) {
        if (rs.next()) {
            final int id = rs.getInt("id"); // pode ser recuperado pela ordem também: rs.getInt(1)
            // faz o que for preciso com os auto gerados
        }
    }
}

I mean, we talk to our statement to popular a ResultSet (recovering by ps.getGeneratedKeys()) with all columns/keys that are auto generated by the database, in our case the serial id.

This Feature may not be supported by all drivers JDBC, then a SQLFeatureNotSupportedException can be cast.

There is also the opposite, when you either do not want in any way such auto generated values to be returned, then you can use PreparedStatement.NO_GENERATED_KEYS and the default behavior depends on the DBMS driver.

  • Thank you Bruno ^-^

  • @Raphaelandrade if this is all you need, consider accept the answer as the correct one :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.