What is Context and Generated Keys?

3

I would like to know what exactly is the context of class connection (I have already seen methods in relation to this as getConnectionFromContext , or something like this) and Generated Keys as the PreparedStattion constant: PreparedStatment.RETURN_GERENERATE_KEYS p>     

asked by anonymous 18.10.2015 / 19:10

1 answer

2

Since you did not include more details about what this context is, I will not assume it is a context of JNDI , a Spring context, ICD, or any other context. Then I will include only the answer to the second question:)

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

The constant PreparedStatement.RETURN_GENERATED_KEYS is used to indicate that auto values generated by the DBMS must be returned after the statement is executed. Let's 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 id will be of type serial , 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");
    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
        }
    }
}

That is, we speak to our statement to popular a ResultSet (retrieving by ps.getGeneratedKeys() ) with all columns / keys that are auto generated by the database, in our case serial id .

This feature may not be supported by all drivers JDBC, then SQLFeatureNotSupportedException can be posted.

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

    
21.11.2015 / 17:21