habuma / spring-in-action-5-samples

Home for example code from Spring in Action 5.
Apache License 2.0
1.21k stars 1.04k forks source link

Ch3: JdbcTacoRepository.saveTacoInfo: keyHolder.getKey() returns null #101

Open glebocki opened 3 years ago

glebocki commented 3 years ago

https://github.com/habuma/spring-in-action-5-samples/blob/ff98b2ec36eeb627e4547713c8acbbd26a0eaa33/ch03/tacos-jdbc/src/main/java/tacos/data/JdbcTacoRepository.java#L38

Following an answer to question on StackOverflow.

JdbcTacoRepository is missing a crucial peace: preparedStatementCreatorFactory.setReturnGeneratedKeys(true);

This is a working method:

private long saveTacoInfo(Taco taco) {
    taco.setCreatedAt(new Date());
    var pscf = new PreparedStatementCreatorFactory(
        "insert into Taco (name, createdAt) values (?, ?)",
        Types.VARCHAR, Types.TIMESTAMP);
    pscf.setReturnGeneratedKeys(true);
    PreparedStatementCreator psc = pscf.newPreparedStatementCreator(
        Arrays.asList(
            taco.getName(),
            new Timestamp(taco.getCreatedAt().getTime())));

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbc.update(psc, keyHolder);

    return keyHolder.getKey().longValue();
}
hbliyafei commented 3 years ago
<properties>
    <!-- H2 1.4.197 breaks auto-incrementing identity columns for some reason -->
    <h2.version>1.4.196</h2.version>
</properties>