I'm trying to use Spring's JdbcTemplate
class to insert a row into a MySQL table named transaction
and get the generated ID. The relevant code is:
public Transaction insertTransaction(final Transaction tran) {
// Will hold the ID of the row created by the insert
KeyHolder keyHolder = new GeneratedKeyHolder();
getJdbcTemplate().update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(INSERT_TRAN_SQL);
ps.setString(1, tran.getTransactionType().toString());
Date sqlDate = new Date(tran.getDate().getTime());
ps.setDate(2, sqlDate);
ps.setString(3, tran.getDescription());
return ps;
}
}, keyHolder);
tran.setId(keyHolder.getKey().longValue());
return tran;
}
But the following exception is thrown by the call to getJdbcTemplate().update
java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement().
Can I insert the row and get the generated ID, without abandoning JdbcTemplate
? I'm using Spring 2.5, MySQL 5.5.27 and MySQL Connector 5.1.26.