Rahul Virpara
Rahul Virpara

Reputation: 1209

Spring JDBC: Auto generated id is not returned even though the row is inserted in table

I am trying to insert row in the table Taco and get the auto generated id.

It throws NPE, when I try to get key using keyHolder.getKey().longValue() in saveTacoInfo method, but it shows the record inserted in the Taco table when I check it from H2-console.

I am using Spring Boot 2.1.0, Spring 5.1.2 and embedded H2 database. How can I resolve this issue?

H2 table schema:

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

Jdbc repository implementation:

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]

Upvotes: 4

Views: 2499

Answers (2)

Mohit Bansal
Mohit Bansal

Reputation: 398

I faced same issue today.

Adding 1.4.196 into com.h2database dependency worked.

Upvotes: 0

wingnet
wingnet

Reputation: 138

I just met the exact same problem.

The solution is simple:

h2 version must 1.4.196, since 1.4.197 would cause this issue. Just specify this version for h2 dependency in pom.xml:

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

Also set the ``parent``` to version 2.0.4.RELEASE. This version will be ok for this problem.

Save pom.xml and check the maven dependencies; make sure the version of h2 and spring boot has been changed correspondingly.

I believe this could solve your problem.

Upvotes: 9

Related Questions