我正在尝试使用Spring的JdbcTemplate
类将一行数据插入到名为transaction
的MySQL表中,并获取生成的ID。相关代码如下:
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;
}
但是,在调用getJdbcTemplate().update
时,会抛出以下异常:
java.sql.SQLException: 未请求生成的键。您需要在Statement.executeUpdate()或Connection.prepareStatement()中指定Statement.RETURN_GENERATED_KEYS。
我可以在不放弃JdbcTemplate
的情况下插入行并获取生成的ID吗? 我正在使用Spring 2.5,MySQL 5.5.27和MySQL Connector 5.1.26。
last_insert_id()
。请参见这里。 - Sotirios Delimanolis