gpt4 book ai didi

java - keyHolder.getKey() 返回 null

转载 作者:行者123 更新时间:2023-12-02 22:56:06 27 4
gpt4 key购买 nike

为什么“Spring in action 5”中的代码不起作用(keyHolder.getKey() 返回 null,但实体保存在数据库中)?

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 实例返回生成的 key :

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())));

关于java - keyHolder.getKey() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53655693/

27 4 0
文章推荐: javascript - 有没有办法确定