21 Mart 2012 Çarşamba

Spring JdbcTemplate get inserted id

Getting the primary key after insertion is done with Spring JdbcTemplate:

        
KeyHolder keyHolder = new GeneratedKeyHolder();
getJdbcTemplate().update(new PreparedStatementCreator() {
     public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
          PreparedStatement ps = connection.prepareStatement(insertSql, new String[]{"id of the corresponding table"});
          return ps;
     }
}, keyHolder);
int insertedId = keyHolder.getKey().intValue();
where insertSql is the query for insertion. The name of the id field is given while preparing the statement. Then after the insertion, the inserted id can be taken GeneratedKeyHolder's key value.

Hiç yorum yok:

Yorum Gönder