Getting the Generated Key using Spring's JdbcTemplate

Monday, October 21, 2019 Labels: , , , , , ,
It is pretty straight forward to have the generated primary key using simple JDBC, but what to do, when you are using Spring's JDBCTemplate.

This is how it's done:

KeyHolder keyHolder = new GeneratedKeyHolder();
        new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps =
                    connection.prepareStatement(INSERT_SQL, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, callString);
                ps.setString(2, storageInsightDTO.getMetadata().getRc());
                return ps;

 System.out.println("generated key: " + keyHolder.getKey());

1.  INSERT_SQL is your native SQL Insert Query

2. Statement.RETURN_GENERATED_KEYS is required to get the generated key.

I hope, you know basic Spring, if you come here and looking for the generated key, then above code is going to be very helpful for you.


Post a Comment

Waqas Sadiq © 2014