Reputation: 1
this is my code
private long saveTacoInfo(Taco taco) {
taco.setCreatedAt(new Date());
PreparedStatementCreator psc =
new PreparedStatementCreatorFactory(
"insert into Taco (name, createdAt) values (?, ?)",
Types.VARCHAR, Types.TIMESTAMP
).newPreparedStatementCreator(
Arrays.asList(
taco.getName(),
new Timestamp(taco.getCreatedAt().getTime())));
KeyHolder keyHolder = new GeneratedKeyHolder();
int res = jdbc.update(psc, keyHolder);
log.info("res " + res);
return keyHolder.getKey().longValue();
}
after debugging, found keyHolder.getKey()
return null, because GeneratedKeyHolder
keyList is empty!
any suggestions?
this is my Taco table sql:
create table if not exists Taco (
id identity,
name varchar(50) not null,
createdAt timestamp not null
);
the Insert
statment is execute ok! h2 database has the data. but keyHolder.getKey
is null.
Upvotes: 0
Views: 578
Reputation: 73
I ran into the same problem as you. Apparently, you used the example from the book "Spring in action".
It seems that the problem in the code, namely in the "PreparedStatementCreatorFactory" class, the "returnGeneratedKeys" field is set to false.
I do not know why the example works in the book or why it is not specified that the variable needs to be changed. The value of this variable, according to Github, has not changed since 2008.
Here is a piece of class code:
public class PreparedStatementCreatorFactory {
/** The SQL, which won't change when the parameters change. */
private final String sql;
/** List of SqlParameter objects (may not be {@code null}). */
private final List<SqlParameter> declaredParameters;
private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
private boolean updatableResults = false;
private boolean returnGeneratedKeys = false;
@Nullable
private String[] generatedKeysColumnNames;
The problem is solved by setting the value of the "returnGeneratedKeys" field to true. Something like this:
var preparedStatementCreatorFactory = new PreparedStatementCreatorFactory(query, Types.VARCHAR, Types.TIMESTAMP);
preparedStatementCreatorFactory.setReturnGeneratedKeys(true);
PreparedStatementCreator preparedStatementCreator =
preparedStatementCreatorFactory
.newPreparedStatementCreator(Arrays.asList(users.getName(), users.getCreateDateTime()));
Upvotes: 3