Thursday, January 12, 2012

Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() using Spring JdbcTemplate

My colleague was getting this exception for a Spring JdbcTemplate based code which I had written for some simple Mysql dao functionalities. The funny point was that we were both using the same version of Mysql drivers, but I was using 32bit Mysql 5.5 but my colleague was using the 64bit version.

This quick fix solves the problem:


KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
 public PreparedStatement createPreparedStatement(Connection aConnection) throws SQLException {
                    PreparedStatement preparedStatement = aConnection.prepareStatement(SAVE_USER,
PreparedStatement.RETURN_GENERATED_KEYS);
                    preparedStatement.setString(....);
                    ....
                         preparedStatement.setString(....);
                    return preparedStatement;
                }
            }, keyHolder);
 user.setId(keyHolder.getKey().intValue());

A few other fellow bloggers had given suggestions like switching the Mysql dirvers, but it's didn't help me at all. I had tried all the last 10 Mysql driver releases. I am not sure if its a programming error or a Mysql bug, but the above code does fix the problem!

Happy Hacking :)

No comments: