jdbcTemplate is null and throws null pointer exception

21,442

In your controller, you are creating a new UserDaoImpl :

@RequestMapping(method = RequestMethod.GET, value="/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<User> getUser(@PathVariable int userId){
    UserDaoImpl user = new UserDaoImpl(); // <-- HERE
    User u = new User();
    u=user.getUser(userId);
    return new ResponseEntity<User>(u, HttpStatus.OK);
}

This UserDaoImpl is not managed by spring, and not configured/autowired. You should inject in your controller the instance of UserDao configured in the xml :

  @Autowired
  private UserDao userDao;

  @RequestMapping(method = RequestMethod.GET, value="/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<User> getUser(@PathVariable int userId){
    User u = userDao.getUser(userId);
    return new ResponseEntity<User>(u, HttpStatus.OK);
}
Share:
21,442
kanra-san
Author by

kanra-san

Updated on February 10, 2020

Comments

  • kanra-san
    kanra-san over 4 years

    I am new to Spring. I am trying to develop REST API using Spring web MVC. I am trying to fetch some data using JdbcTemplate from my database (MySQL). But when i run the code in the server I am getting 500- Internal Server Error and the stack trace shows java.lang.NullPointerException. When i tried to debug the code i found out that jdbcTemplate variable has null value. I have tried every solution provided in web but still getting the same error.

    Here is my applicationContext.xml file

        <context:component-scan base-package="com.cinema.repository" />
    
    
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource" />
        </bean>
        <bean id="userDao" class="com.cinema.repository.UserDaoImpl">
            <property name="jdbcTemplate" ref="jdbcTemplate" />
        </bean>
        <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
        </bean>
    
        <context:property-placeholder location="/WEB-INF/jdbc.properties" />
    

    My UserDaoImpl.java looks is:

    public class UserDaoImpl implements UserDao {
    private JdbcTemplate jdbcTemplate;
    
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    public User getUser(int userId) {
        String sql ="SELECT * FROM user_tbl WHERE user_id = ?";
        return this.jdbcTemplate.queryForObject(sql,new Object[]{new Integer(userId)}, new UserMapper() );
    }
    
    private static final class UserMapper implements RowMapper<User>{
        public User mapRow(ResultSet rs, int rowCount) throws SQLException {
            User u = new User();
            u.setUserId(rs.getInt("user_id"));
            u.setUserName(rs.getString("username"));
            u.setPassword(rs.getString("password"));
            u.setEmailId(rs.getString("email"));
            u.setRole(rs.getString("role"));
            return u;
        }
      }
    }
    

    And my controller class is UserController.java:

    @RestController
    @RequestMapping(value="/user")
    public class UserController {
        @RequestMapping(method = RequestMethod.GET, value="/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE})
        ResponseEntity<User> getUser(@PathVariable int userId){
            UserDaoImpl user = new UserDaoImpl();
            User u = new User();
            u=user.getUser(userId);
            return new ResponseEntity<User>(u, HttpStatus.OK);
        }
    }
    

    and i am getting the following stack trace while running the application:

    10-Feb-2016 02:50:28.165 SEVERE [tomcat-http--5] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [spring] in context with path [/booking] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
    java.lang.NullPointerException
    at com.cinema.repository.UserDaoImpl.getUser(UserDaoImpl.java:31)
    at com.cinema.web.UserController.getUser(UserController.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:277)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
    

    Please tell me what i am doing wrong here. I have been stuck on this problem for a week now and still cannot make my code work. Thanks in advance.

  • duffymo
    duffymo over 8 years
    Right - calling new means Spring is not involved; you are responsible from then on. It's all or nothing: either Spring handles the creation and DI or you do.
  • Philip Rego
    Philip Rego about 3 years
    My UserDao is autowired, implements JdbcDaoSupport and calls setDataSource() with a good datasource, but getJdbcTemplate() is null. Someone please give full answer.
  • Jérémie B
    Jérémie B about 3 years
    @PhilipRego you should probably ask your own question instead of downvoting an accepted answer for another issue.
  • Philip Rego
    Philip Rego about 3 years
    I didn't want to ask a duplicate question and your answer didn't work for me. queryForObject was giving NPE because an int (primitive type) was assigned to queryForObject.