gpt4 book ai didi

java - 如何在 Spring Boot 中使用 KeyHolder?

转载 作者:行者123 更新时间:2023-11-30 05:27:58 25 4
gpt4 key购买 nike

我尝试通过以下代码使用 Spring Boot JdbcTamplate 将数据保存到 H2 数据库:

架构.sql:

create table if not exists Taco (
id identity,
name varchar(50) not null,
createdAt timestamp not null
);

这是我的存储库类:

public class JdbcTacoRepository {
public 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();
jdbc.update(psc, keyHolder);

return Objects.requireNonNull(
keyHolder.getKey() // in this place keyHolder.getKey() is null
).longValue();
}
}

但是在调用jdbc.update(psc, keyholder);之后,我得到keyHolder is Null引用对象。

我做错了什么?请帮助我。

最佳答案

尝试添加

preparedStatementCreatorFactory.setReturnGeneratedKeys(true);

在使用 PreparedStatementCreatorFactory 创建 PreparedStatementCreator 之前。然后创建的 psc 应该返回生成的 key ,然后可以由 KeyHolder 获取该 key 。

关于java - 如何在 Spring Boot 中使用 KeyHolder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58178992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com