插入行并获取生成的 ID

2024-02-13

我正在尝试使用 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;
}

但调用时抛出以下异常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);

然后创建一个名为parameters 的映射,其中包含表中每个列名称的值,并插入如下记录:

    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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

插入行并获取生成的 ID 的相关文章

随机推荐