Skip to content

Instantly share code, notes, and snippets.

@RICH0423
Last active December 14, 2016 07:04
Show Gist options
  • Select an option

  • Save RICH0423/3649e5a314dae37cf0a9ff3fc9be12c2 to your computer and use it in GitHub Desktop.

Select an option

Save RICH0423/3649e5a314dae37cf0a9ff3fc9be12c2 to your computer and use it in GitHub Desktop.
JdbcTemplate Retrieving auto-generated keys
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
public void insert() {
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
}
@RICH0423

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment