一尘不染

通过jdbctemplate从sql插入身份

spring

在Spring jdbc模板调用中,是否可以从SQL插入中获取@@ identity?如果是这样,怎么办?


阅读 204

收藏
2020-04-17

共1个答案

一尘不染

JDBCTemplate.update方法已重载,以获取一个称为GeneratedKeyHolder的对象,你可以使用该对象来检索自动生成的密钥。例如:

final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
    new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps =
                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
            ps.setString(1, name);
            return ps;
        }
    },
    keyHolder);
// keyHolder.getKey() now contains the generated key
2020-04-17