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");

}

No comments: