I got a very common question when I was using Spring JDBCTemplate, I want to get the ID value after I inserted a new data record into database, this ID value will be referred to another related table. I tried the following way to insert it, but I always return 1 rather than its real unique ID. (I use MySQL as the database)
public int insert(BasicModel entity) {
String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);
log.info("SQL Statement for inserting into: " + insertIntoSql);
return this.jdbcTemplate.update(insertIntoSql);
}
JdbcTemplate.update()
returns:Which is always
1
forINSERT
statement. Different databases support generated key extraction in different ways, but most JDBC drivers abstract this andJdbcTemplate
supports this. Quoting 12.2.8 Retrieving auto-generated keysBasically you need this much more verbose statement: