查看文档命名参数Jdbc模板 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.html and Jdbc模板 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html你有两个选择:
use NamedParameterJdbcTemplate
's update http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.html#update-java.lang.String-org.springframework.jdbc.core.namedparam.SqlParameterSource-org.springframework.jdbc.support.KeyHolder- method.
use JdbcTemplate
's update http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html#update-org.springframework.jdbc.core.PreparedStatementCreator-org.springframework.jdbc.support.KeyHolder- method.
还有一些其他可用的方法可以将键填充到给定的生成的KeyHolder https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/support/GeneratedKeyHolder.html,由您决定哪一个适合您的需求。
EDIT
例如使用 JdbcTemplate:
GeneratedKeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement statement = con.prepareStatement("INSERT INTO SOME_TABLE(NAME, VALUE) VALUES (?, ?) ", Statement.RETURN_GENERATED_KEYS);
statement.setString(1, "SomeName");
statement.setString(2, "SomeValue");
return statement;
}
}, holder);
long primaryKey = holder.getKey().longValue();