我得到由数据库(MSSQL)生成的id后插入如下,导入:
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.SqlReturnResultSet;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
和代码片段:
final String INSERT_SQL = "INSERT INTO [table]\n"
+ " ([column_1]\n"
+ " ,[column_2])\n"
+ " VALUES\n" +
" (?, ?)";
Connection connection = jdbcTemplate.getDataSource().getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_INVOICE_SQL, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, "test 1");
preparedStatement.setString(2, "test 2");
preparedStatement.executeUpdate();
ResultSet keys = preparedStatement.getGeneratedKeys();
if (keys.next()) {
Integer generatedId = keys.getInt(1); //id returned after insert execution
}