0

I want to make use of spring JdbcTemplate to insert a line and return the id autogenerated by the mysql db.

Without spring I'd do similar as follows:

String sql = "INSERT INTO mytable (id, filename, timestamp) VALUES (NULL, ?, NOW())";
Statement st = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

st.setString("test.csv");
st.executeUpdate();
st.getGeneratedKeys().next().getLong(1);

Question: how could I achive the same with JdbcTemplate?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

1 Answers1

1

In short its

 Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(
                parameters));

You can check my answer in identity from sql insert via jdbctemplate

Community
  • 1
  • 1
Sheetal Mohan Sharma
  • 2,908
  • 1
  • 23
  • 24
  • 1
    Where would I add my sql statement there? – membersound May 11 '17 at 08:33
  • Can you please check the thread I shared, you can find other ways to achieve this including the SQL one. If you want to stick to SQL statement, then I guess you can use the KeyHolder with update statement or call jdbcTemplate.queryForInt() after insert statement has been called. – Sheetal Mohan Sharma May 11 '17 at 08:38