Java 如何在弹簧靴中使用钥匙夹?
我尝试通过以下代码使用Spring Boot JdbcTamplate将数据保存到H2数据库: schema.sql:Java 如何在弹簧靴中使用钥匙夹?,java,spring-boot,spring-data,Java,Spring Boot,Spring Data,我尝试通过以下代码使用Spring Boot JdbcTamplate将数据保存到H2数据库: schema.sql: create table if not exists Taco ( id identity, name varchar(50) not null, createdAt timestamp not null ); 这是我的存储库类: public class JdbcTacoRepository { public long saveTacoInf
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.updatepsc,keyholder之后;我得到的keyHolder是空引用对象
我做错了什么?
请帮助我。尝试添加
preparedStatementCreatorFactory.setReturnGeneratedKeys(true);
使用PreparedStatementCreatorFactory创建PreparedStatementCreator之前。然后,创建的psc应该返回生成的密钥,然后可以由KeyHolder拾取。您得到的是null的KeyHolder还是KeyHolder.getKey?@Ankur在我的情况下KeyHolder.getKey为null。@buræquete谢谢您的帮助!建议添加preparedStatementCreatorFactory.setReturnGeneratedKeystrue;工作正常!