0

It's from Spring in Action ch03 JDBC The taco object is always null. Taco saved = designRepo.save(taco) throws null pointer exception --updated as below, thanks JB Nizet -- It's from Spring in Action ch03 JDBC designRepo is null Taco saved = designRepo.save(taco) throws null pointer exception Unable to figure out where jdbc (in JdbcTacoRepository) is instantiated

Controller

@PostMapping
  public String processDesign(
          @Valid @ModelAttribute("taco") Taco taco, Errors errors, 
      @ModelAttribute Order order) {

    if (errors.hasErrors()) {
      return "design";
    }

    log.info("post: ", taco.toString());

    //the below line throws null pointer exception, hence commented
    //Taco saved = designRepo.save(taco);
    //order.addDesign(saved);

    return "redirect:/orders/current";
  }

Converter

@Component
public class IngredientByIdConverter implements Converter<String, Ingredient> {

  private IngredientRepository ingredientRepo;

  @Autowired
  public IngredientByIdConverter(IngredientRepository ingredientRepo) {
    this.ingredientRepo = ingredientRepo;
  }

  @Override
  public Ingredient convert(String id) {
    return ingredientRepo.findOne(id);
  }

}

JdbcTacoRepository

@Repository
public class JdbcTacoRepository implements TacoRepository {

  private JdbcTemplate jdbc;

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

  @Override
  public Taco save(Taco taco) {
    long tacoId = saveTacoInfo(taco);
    taco.setId(tacoId);
    for (Ingredient ingredient : taco.getIngredients()) {
      saveIngredientToTaco(ingredient, tacoId);
    }

    return taco;
  }

  private 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 keyHolder.getKey().longValue();
  }

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

}

Log

2019-12-22 01:34:48.717 TRACE 59846 --- [http-nio-8080-exec-4] .w.s.m.m.a.ServletInvocableHandlerMethod : Arguments: [Taco [name=TacoName1122, ingredients=[Ingredient [id=COTO, name=Corn Tortilla, type=WRAP], Ingredient [id=CARN, name=Carnitas, type=PROTEIN]], id=null, createdAt=null], org.springframework.validation.BeanPropertyBindingResult: 0 errors, com.mani.tacos.model.Order@14de87fe]
2019-12-22 01:34:48.718  INFO 59846 --- [http-nio-8080-exec-4] c.m.tacos.controller.DesignController    : post: Taco [name=TacoName1122, ingredients=[Ingredient [id=COTO, name=Corn Tortilla, type=WRAP], Ingredient [id=CARN, name=Carnitas, type=PROTEIN]], id=null, createdAt=null]
2019-12-22 01:34:48.726 TRACE 59846 --- [http-nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Failed to complete request
Sun Dec 22 01:34:48 SGT 2019
    There was an unexpected error (type=Internal Server Error, status=500).
    No message available
    java.lang.NullPointerException
        at com.mani.tacos.repository.JdbcTacoRepository.saveTacoInfo(JdbcTacoRepository.java:54)
        at com.mani.tacos.repository.JdbcTacoRepository.save(JdbcTacoRepository.java:31)
        at com.mani.tacos.repository.JdbcTacoRepository$$FastClassBySpringCGLIB$$9c06a39c.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
        at com.mani.tacos.repository.JdbcTacoRepository$$EnhancerBySpringCGLIB$$8e0297b.save(<generated>)
        at com.mani.tacos.controller.DesignController.processDesign(DesignController.java:92)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:834)

POM

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

properties

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
michael
  • 661
  • 1
  • 7
  • 18
  • Replace `log.info("post: ", taco.toString());` by `log.info("post: " + taco);`. Or, if you're using Slf4J, by `log.info("post: {}", taco);`. Voting to close for typo. – JB Nizet Dec 21 '19 at 17:15
  • It's not the log.info problem. The taco object is null. When I try the next line Taco saved = designRepo.save(taco); I get null pointer which means taco is null – michael Dec 21 '19 at 17:20
  • 1
    No. It probably means designRepo is null. Do as I told you, post the new logs, post the relevant code, post the stack trace of the exception. – JB Nizet Dec 21 '19 at 17:21
  • You didn't fiw the log statement, which doesn't help knowing what the value of taco is. What's the line 54 of JdbcTacoRepository.java? – JB Nizet Dec 21 '19 at 17:48
  • Line 54: return keyHolder.getKey().longValue(); Updated the log. Shouldn't somwhere I need to define what jdbc is? – michael Dec 21 '19 at 17:50
  • 1
    So taco is not null, otherwise you would have the exception sooner. keyHolder can't be null since you initialized it just before. So keyHolder.getKey() is null. You haven't called https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/PreparedStatementCreatorFactory.html#setReturnGeneratedKeys-boolean-, so that's most probably the reason. – JB Nizet Dec 21 '19 at 17:55
  • 1
    @JBNizet Thanks a lot. I've been stuck at this for past 3-4 days. I also learnt how to read log and figure out where the actual error is – michael Dec 21 '19 at 18:12
  • We meet this problem too. I think this question can help us. https://stackoverflow.com/questions/53655693/keyholder-getkey-return-null – xiahaoyun May 24 '20 at 11:19

0 Answers0