Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在弹簧靴中使用钥匙夹?_Java_Spring Boot_Spring Data - Fatal编程技术网

Java 如何在弹簧靴中使用钥匙夹?

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

我尝试通过以下代码使用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 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;工作正常!