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

后端 未结 3 1896
我寻月下人不归
我寻月下人不归 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: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.

提交回复
热议问题