Spring JDBC:即使将行插入表中,也不会返回自动生成的ID

时间:2018-11-10 06:36:53

标签: java spring h2 spring-jdbc

我正在尝试在表Taco中插入行并获取自动生成的ID。

当我尝试在keyHolder.getKey().longValue()方法中使用saveTacoInfo获取密钥时,它抛出NPE,但是当我从H2控制台对其进行检查时,它显示了插入到Taco表中的记录。

我正在使用Spring Boot 2.1.0,Spring 5.1.2和嵌入式H2数据库。我该如何解决这个问题?

H2表架构:

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

Jdbc存储库实施:

package tacos.data;

import java.sql.Timestamp;
import java.sql.Types;
import java.util.Arrays;
import java.util.Date;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementCreatorFactory;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import lombok.extern.slf4j.Slf4j;
import tacos.Taco;

@Slf4j
@Repository
public class JdbcTacoRepository implements TacoRepository {

    private JdbcTemplate jdbc;

    public JdbcTacoRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    @Override
    public Taco save(Taco taco) {
        long tacoId = saveTacoInfo(taco);
        taco.setId(tacoId);

        for (String ingredient : taco.getIngredients()) {
            saveIngredientToTaco(ingredient, tacoId);
        }

        return taco;
    }

    private void saveIngredientToTaco(String ingredient, long tacoId) {
        jdbc.update("insert into Taco_Ingredients (taco, ingredient) values (?, ?)",
                tacoId, ingredient);

    }

    private long saveTacoInfo(Taco taco) {
        taco.setCreatedAt(new Date());

        log.info("taco: " + taco);

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

        log.info("keyholder: " + keyHolder.getKeyList());
        return keyHolder.getKey().longValue();
    }


}

Stacktrace

2018-11-10 11:18:34.459  INFO 4024 --- [nio-8080-exec-3] tacos.data.JdbcTacoRepository            : taco: Taco(id=null, createdAt=Sat Nov 10 11:18:34 IST 2018, name=ccccccc, ingredients=[GRBF, CARN])
2018-11-10 11:18:34.542  INFO 4024 --- [nio-8080-exec-3] tacos.data.JdbcTacoRepository            : keyholder: []
2018-11-10 11:18:34.597 ERROR 4024 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
    at tacos.data.JdbcTacoRepository.saveTacoInfo(JdbcTacoRepository.java:63) ~[classes/:na]
    at tacos.data.JdbcTacoRepository.save(JdbcTacoRepository.java:31) ~[classes/:na]
    at tacos.data.JdbcTacoRepository$$FastClassBySpringCGLIB$$59d8a28e.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at tacos.data.JdbcTacoRepository$$EnhancerBySpringCGLIB$$996b212f.save(<generated>) ~[classes/:na]
    at tacos.web.DesignTacoController.processDesign(DesignTacoController.java:85) ~[classes/:na]

2 个答案:

答案 0 :(得分:5)

我刚刚遇到了完全相同的问题。

解决方案很简单:

1个密码正确。

2 h2版本必须为1.4.196,因为1.4.197会导致此问题。

3删除pom.xml中h2的依赖项。

4将文本添加到pom.xml。

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
   <version>1.4.196</version>
</dependency>

“父”部分中的5,将版本更改为2.0.4.RELEASE,此版本可以解决此问题。

保存pom.xml并检查Maven依赖关系,确保h2和spring boot的版本已相应更改。

我相信这可以解决您的问题。

答案 1 :(得分:0)

我今天也遇到同样的问题。

将1.4.196添加到com.h2database依赖项是可行的。