【发布时间】:2013-10-06 10:06:17
【问题描述】:
我正在尝试使用 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.RETURN_GENERATED_KEYS 以 Statement.executeUpdate() 或 Connection.prepareStatement()。
我可以在不放弃JdbcTemplate的情况下插入行并获取生成的ID吗?我正在使用 Spring 2.5、MySQL 5.5.27 和 MySQL Connector 5.1.26。
【问题讨论】:
-
对于 MySQL,我认为您需要致电
last_insert_id()。见here。
标签: java jdbctemplate spring-jdbc