Last active
December 14, 2016 07:04
-
-
Save RICH0423/3649e5a314dae37cf0a9ff3fc9be12c2 to your computer and use it in GitHub Desktop.
JdbcTemplate Retrieving auto-generated keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: http://docs.spring.io/spring/docs/4.3.4.RELEASE/spring-framework-reference/html/jdbc.html#jdbc-auto-genereted-keys