Spring: How to use KeyHolder with PostgreSQL Spring: How to use KeyHolder with PostgreSQL spring spring

Spring: How to use KeyHolder with PostgreSQL


If the framework is not informed about which column is the key, it will return all columns of the table as keys.

You can inform it by passing a new parameter to the update method, as follows:

template.update(query, data, keyHolder, new String[] { "id" });

See NamedParameterJdbcTemplate.update(sql, paramSource, generatedKeyHolder, keyColumnNames)


You can also stay with JdbcTemplate but in this situation you have to check it:

    jdbcTemplate.update(this, holder);    Long newId;    if (holder.getKeys().size() > 1) {        newId = (Long)holder.getKeys().get("your_id_column");    } else {        newId= holder.getKey().longValue();    }

The GeneratedKeyHolder class throws exception due to the fact that class only knows what should be returned when has one key (and that key needs to be Number instance because getKey method returns Number object).

On situation when jdbc driver return multiple keys you have to determine the generated key column (either before update or after). Please take a look at source code of the GeneratedKeyHolder#getKey - it is very simple to analyze. There is checking of key list size and with more than key Spring does not know which key should be returned and that's why the exception is returned.

Note: Please remember that approach won't work with Oracle because Oracle returns something like ROWID. With Oracle you have to use NamedParameterJdbcTemplate.


Just a guess from a quick look... keyHolder.getKey().intValue() should be keyHolder.getKey()["id"].intValue() (or something similar)? getKey() function returns an object with multiple keys (id and image) and you are trying to turn the object to int with intValue() function which I guess does not work unless you point to the "id" key in the object returned from "getKey()"Cheers,Francesco