7.08.2011

Resolving Postgres "returning auto generated keys no supported"

I discovered Jean-Pol Landrain's, "TriggerAssignedIdentityGenerator" to address the issue of the Hibernate ID Generator not supporting an Id created by the database via a BEFORE INSERT trigger.

However the TriggerAssignedIdentityGenerator design for Oracle did not work for the older JDBC PostgreSQL driver which doesn't support the return of auto-generated keys.

The probem was resolved by changes to the 'prepare' and 'executeAndExtract' methods:




protected PreparedStatement prepare(String insertSQL, SessionImplementor session) throws SQLException {

return session.getBatcher().prepareStatement(insertSQL + " RETURNING *");
}

protected Serializable executeAndExtract(PreparedStatement insert) throws SQLException {

insert.execute();
// get the new id back
ResultSet rs = insert.getResultSet();
if (rs.next()) {
return new String(rs.getString(1)); // assume that 1 is id
}

throw new SQLException("Returned no id in resultset");

}

postgres create trigger error relation does not exist 42P01

PostgreSQL 8.4: When attempting to create a simple trigger the executes a function, for a table that exists, I was getting a 42P01 error: relation "table_name" does not exist

CREATE TRIGGER genUuid
BEFORE INSERT ON table_name
FOR EACH ROW EXECUTE PROCEDURE generate_function_v1();

This was simple resolved by including the schema name along with the table as follows:

CREATE TRIGGER genUuid
BEFORE INSERT ON my_schma.table_name
FOR EACH ROW EXECUTE PROCEDURE generate_function_v1();