How can I get the autoincremented id when I insert a record in a table via jdbctemplate

后端 未结 3 1885
我寻月下人不归
我寻月下人不归 2020-12-15 23:16
private void insertIntoMyTable (Myclass m) {
    String query = \"INSERT INTO MYTABLE (NAME) VALUES (?)\";
    jdbcTemplate.update(query, m.getName());
}


        
相关标签:
3条回答
  • 2020-12-15 23:18

    I get id generated by database (MSSQL) after insert like below, imports:

      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;
    

    and the code snippet:

        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
        } 
    
    0 讨论(0)
  • 2020-12-15 23:21

    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
    
    0 讨论(0)
  • 2020-12-15 23:21

    JdbcTemplate is at the core of Spring. Another option is to use SimpleJdbcInsert.

    SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
    simpleJdbcInsert
        .withTableName("TABLENAME")
        .usingGeneratedKeyColumns("ID");
    SqlParameterSource params = new MapSqlParameterSource()
        .addValue("COL1", model.getCol1())
        .addValue("COL2", model.getCol2());
    Number number = simpleJdbcInsert.executeAndReturnKey(params);   
    

    You can still @Autowire jdbcTemplate. To me, this is more convenient than working with jdbcTemplate.update() method and KeyHolder to get the actual id.

    Example code snippet is tested with Apache Derby and should work with the usual databases.

    Use of Spring JPA is another option - if ORM is for you.

    0 讨论(0)
提交回复
热议问题