本文介绍了keyHolder.getKey()返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么"Spring in Action 5"中的代码不起作用(keyHolder.getKey()返回null,但是实体保存在DB中)?
Why code from "Spring in action 5" don't work (keyHolder.getKey() return null, but entity is saved in DB)?
private long savePizzaInfo(Pizza pizza) {
pizza.setCreatedAt(new Date());
PreparedStatementCreator psc =
new PreparedStatementCreatorFactory(
"insert into PIZZA (name, createdAt) values (?, ?)",
Types.VARCHAR, Types.TIMESTAMP
).newPreparedStatementCreator(
Arrays.asList(
pizza.getName(),
new Timestamp(pizza.getCreatedAt().getTime())));
KeyHolder keyHolder = new GeneratedKeyHolder();
template.update(psc, keyHolder);
return keyHolder.getKey().longValue();
}
我的数据库表:
CREATE TABLE PIZZA
(
ID bigint DEFAULT (NEXT VALUE FOR
PUBLIC.SYSTEM_SEQUENCE_12CA966F_4FFD_469C_BA69_80BB93916EF3) AUTO_INCREMENT
PRIMARY KEY NOT NULL,
NAME varchar(50) NOT NULL,
CREATEDAT timestamp NOT NULL
);
CREATE UNIQUE INDEX PRIMARY_KEY_4 ON PIZZA (ID);
推荐答案
您必须指示PreparedStatementCreatorFactory
实例返回生成的密钥:
You have to instruct PreparedStatementCreatorFactory
instance to return the generated keys:
PreparedStatementCreatorFactory preparedStatementCreatorFactory = new PreparedStatementCreatorFactory(
"insert into PIZZA (name, createdAt) values (?, ?)",
Types.VARCHAR, Types.TIMESTAMP
);
// By default, returnGeneratedKeys = false so change it to true
preparedStatementCreatorFactory.setReturnGeneratedKeys(true);
PreparedStatementCreator psc =
preparedStatementCreatorFactory.newPreparedStatementCreator(
Arrays.asList(
pizza.getName(),
new Timestamp(pizza.getCreatedAt().getTime())));
这篇关于keyHolder.getKey()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!