Dón*_*nal 6 java spring-jdbc jdbctemplate
我正在尝试使用Spring的JdbcTemplate类在名为MySQL的表中插入一行transaction并获取生成的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;
}
Run Code Online (Sandbox Code Playgroud)
但是调用引发了以下异常 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.
有一种更简单的方法来获得这种行为:
protected JdbcTemplate jdbcTemplate;
private SimpleJdbcInsert insert;
this.jdbcTemplate = new JdbcTemplate(this.databaseSetup.getDataSource());
this.insert = new SimpleJdbcInsert(this.jdbcTemplate).withTableName(this.tableName).usingGeneratedKeyColumns(this.pkColumn);
Run Code Online (Sandbox Code Playgroud)
然后创建一个名为parameters的Map,它包含表中每个列名的值,并插入如下记录:
final Map<String, Object> parameters = new HashMap<>();
parameters.put("empName", employee.getName()); // store the String name of employee in the column empName
parameters.put("dept", employee.getDepartment()); // store the int (as Integer) of the employee in the column dept
final Number key = this.insert.executeAndReturnKey(parameters);
final long pk = key.longValue();
Run Code Online (Sandbox Code Playgroud)
请准备好Statement以下内容
PreparedStatement ps = connection.prepareStatement(
INSERT_TRAN_SQL, Statement.RETURN_GENERATED_KEYS);
Run Code Online (Sandbox Code Playgroud)
底层JDBC驱动程序(JdbcTemplate在这里通过Spring间接使用)需要提示您要检索生成的密钥.这可以在准备PreparedStatementas时完成
connection.prepareStatement(strSQL, Statement.RETURN_GENERATED_KEYS);
Run Code Online (Sandbox Code Playgroud)
或者,在执行Statementas时
statement.executeUpdate(strSQL, Statement.RETURN_GENERATED_KEYS);
Run Code Online (Sandbox Code Playgroud)
这也是你java.sql.SQLException所指的.
| 归档时间: |
|
| 查看次数: |
22656 次 |
| 最近记录: |