java – What is Context and Generated Keys?


I would like to know exactly what the context of the connection class is (I've seen methods for this like getConnectionFromContext , or something like that) and Generated Keys like the PreparedStatment constant: PreparedStatment.RETURN_GERENERATE_KEYS


Since you haven't included more details about what this context is, I won't assume it's a JNDI context, a Spring, CDI context, or any other. So I just included answer to the second question 🙂

Generated Keys are attributes generated automatically by the DBMS, such as row id , identities , values ​​generated by triggers, etc. In JDBC, as of version 3, you can explicitly tell the statement whether or not you want such values ​​to be returned in a ResultSet .

The constant PreparedStatement.RETURN_GENERATED_KEYS is used to indicate that DBMS auto-generated values ​​should be returned after executing the statement . Let's say you have the following table (using PostgreSQL as an example):

  id serial NOT NULL,
  nome character varying(300),
  CONSTRAINT pessoa_id_pk PRIMARY KEY (id)

We say that the id will be of the serial type, which 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");
    try (final ResultSet rs = ps.getGeneratedKeys()) {
        if ( {
            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

That is, we ps.getGeneratedKeys() our statement to populate a ResultSet (retrieving 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 JDBC drivers , so a SQLFeatureNotSupportedException may be thrown.

There is also the reverse, when you want to not want such auto-generated values ​​to be returned at all, then you can use PreparedStatement.NO_GENERATED_KEYS and the default behavior depends on the DBMS driver.

Scroll to Top