Unsure how to return generated column id value using Spring jdbcTemplate and PreparedStatementSetter

前端 未结 1 968
一生所求
一生所求 2021-01-13 03:58

Before refactoring, I was inserting a row into the db using jdbcTemplate, preparedStatementCreator and a GeneratedKeyHolder to store the generated id of the inserted row.

相关标签:
1条回答
  • 2021-01-13 04:54

    Generated keys may be returned with JdbcTemplate#update(PreparedStatementCreator,KeyHolder) method. But to achieve this you need to change your request, based on org.springframework.jdbc.core.PreparedStatementCreatorFactory.

    Instead I would recommend to use for inserting SimpleJdbcInsert utility class.

    If your DB fields are the very same as your entities' fields, then you can simply do as following:

    Number key = jdbcInsert.executeAndReturnKey(new BeanPropertySqlParameterSource(entity));
    //set generated key
    if (key != null){
        entity.setId(key.longValue());
    }
    

    If it is not (as in your case), then

    //define parameters
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("FIRSTNAME", pupil.getFirstname());
    parameters.put("SURNAME", pupil.getSurname());
    parameters.put("GIVEN_NAME", pupil.getGivenName());
    parameters.put("DOB", pupil.getDob());
    //execute insert
    Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(parameters));
    //set generated key
    if (key != null){
        pupil.setId(key.longValue());
    }
    

    jdbcInsert parameter you need to define once for each entity, and it will look like the following:

    SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(getJdbcTemplate());
    
    jdbcInsert.withTableName(entityName); //e.g. "STUDENTS"
    
    jdbcInsert.setGeneratedKeyName(idColumn); //e.g. "ID"
    
    jdbcInsert.setColumnNames(columnNames); //e.g. Arrays.asList("FIRSTNAME", "SURNAME", "GIVEN_NAME", "DOB")
    
    0 讨论(0)
提交回复
热议问题