How to get the generated identifier after entering data into the database in a new record using Spring JDBCTemplate?

I had a very common question, when I used Spring JDBCTemplate, I want to get the ID value after I inserted a new data record into the database, this ID value will be transferred to another related table. I tried the following way to insert it, but I always return 1, not its unique unique identifier. (I use MySQL as a database)

public int insert(BasicModel entity) {
    String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);

    log.info("SQL Statement for inserting into: " + insertIntoSql);

    return this.jdbcTemplate.update(insertIntoSql);
}
+5
source share
1 answer

JdbcTemplate.update() returns:

number of rows affected

1 INSERT. -, JDBC , JdbcTemplate . 12.2.8

update() , . JDBC 3.0; . 13.6 .

:

final String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);
KeyHolder keyHolder = new GeneratedKeyHolder();

jdbcTemplate.update(
  new PreparedStatementCreator() {
    public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
      return connection.prepareStatement(insertIntoSql, new String[] {"id"});
    }
  }, keyHolder);

return keyHolder.getKey().intValue();
+6

All Articles