Issue
private void insertIntoMyTable (Myclass m) {
String query = "INSERT INTO MYTABLE (NAME) VALUES (?)";
jdbcTemplate.update(query, m.getName());
}
When the above query inserts a record, the ID
column in the table autoincrements.
Is there a way to get this auto incremented ID back at the time of the insertion. So in this example the return value of my method would be int
Solution
Check this reference. You can use jdbcTemplate.update as:
EDIT Added imports as asked
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
following is the code usage:
final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps =
connection.prepareStatement(INSERT_SQL, new String[] {"id"});
ps.setString(1, name);
return ps;
}
},
keyHolder);
// keyHolder.getKey() now contains the generated key
Answered By - Anshu
Answer Checked By - David Marino (JavaFixing Volunteer)