我試圖使用Spring的JdbcTemplate
類將行插入名爲transaction
的MySQL表中並獲取生成的ID。相關的代碼是:插入行並生成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.RETURN_GENERATED_KEYS指定爲 Statement.executeUpdate()或Connection.prepareStatement()。
我可以插入行並獲取生成的ID,而不會丟棄JdbcTemplate
?我使用Spring 2.5,MySQL 5.5.27和MySQL Connector 5.1.26。
用MySQL,我想你會需要調用'LAST_INSERT_ID()'。參見[這裏](http://stackoverflow.com/questions/7501464/how-to-get-the-id-of-inserted-row-in-mysql)。 –