Spring boot JPA CrudRepository throws NullPointerException on save

14,632

This happens because you autowired only the ApiRepository field.

The @Autowired applies to the first below field, not to all fields in the class, you need to add the annotation on every field you want to inject.

@Autowired(required = true)
private ApiRepository ApiRepo;
@Autowired(required = true)
private TwitterRepository TwitRepo;
Share:
14,632
kakashi hatake
Author by

kakashi hatake

I am a computer engineer interested in java technology and Javascript frameworks currently vue.js

Updated on November 29, 2022

Comments

  • kakashi hatake
    kakashi hatake over 1 year

    When I try to save data and list by a restful web service, I get the NullPointerException error

    ApiRestService.java

    package com.twitterservice.service;
    @RestController
    public class ApiRestService {
    
        private static final Logger logger = LoggerFactory.getLogger(ApiRestService.class);
    
        @Autowired(required = true)
        ApiRepository ApiRepo;
        TwitterRepository TwitRepo;
    
        @RequestMapping(value = "/rest/twitterapi", method = RequestMethod.POST, produces = "application/json")
        @ResponseBody
        public ResponseEntity<ApiDomain> saveApiKeys(@RequestBody ApiDomain request) {
            ApiRepo.save(request);
            return new ResponseEntity<ApiDomain>(request, HttpStatus.OK);
    
        }
    
        @RequestMapping(value = "/rest/twitter", method = RequestMethod.GET)
        @SuppressWarnings("empty-statement")
        public Iterable<TwitterDomain> getAll() throws TwitterException {
            ApiDomain apikeys = ApiRepo.findOne(1L);
            ConfigurationBuilder xb = new ConfigurationBuilder();
            xb.setDebugEnabled(true)
                    .setOAuthConsumerKey(apikeys.getConsumerKey())
                    .setOAuthConsumerSecret(apikeys.getConsumerSecret())
                    .setOAuthAccessToken(apikeys.getAccessToken())
                    .setOAuthAccessTokenSecret(apikeys.getAccessTokenSecret());
    
            TwitterFactory tf = new TwitterFactory(xb.build());
            twitter4j.Twitter tw = tf.getInstance();
            List<Status> statuses = tw.getHomeTimeline();
            for (Status a : statuses) {
    
                TwitRepo.save(new TwitterDomain(a.getUser().getName(), a.getText(), "stable"));
    
            }
    
            Iterable<TwitterDomain> lst = TwitRepo.findAll();
    
            return lst;
        }
    }
    

    ApiDomain.java

    package com.twitterservice.dao;
    @Entity
    public class ApiDomain implements Serializable {
        
        
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private long id;
        private String accountName;
        private String consumerKey;
        private String consumerSecret;
        private String accessToken;
        private String accessTokenSecret;
    
        public long getId() {
            return id;
        }
    
        public void setId(long id) {
            this.id = id;
        }
    
        public String getAccountName() {
            return accountName;
        }
    
        public void setAccountName(String accountName) {
            this.accountName = accountName;
        }
    
        public String getConsumerKey() {
            return consumerKey;
        }
    
        public void setConsumerKey(String consumerKey) {
            this.consumerKey = consumerKey;
        }
    
        public String getConsumerSecret() {
            return consumerSecret;
        }
    
        public void setConsumerSecret(String consumerSecret) {
            this.consumerSecret = consumerSecret;
        }
    
        public String getAccessToken() {
            return accessToken;
        }
    
        public void setAccessToken(String accessToken) {
            this.accessToken = accessToken;
        }
    
        public String getAccessTokenSecret() {
            return accessTokenSecret;
        }
    
        public void setAccessTokenSecret(String accessTokenSecret) {
            this.accessTokenSecret = accessTokenSecret;
        }
    
        public ApiDomain(String accountName, String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) {
            this.accountName = accountName;
            this.consumerKey = consumerKey;
            this.consumerSecret = consumerSecret;
            this.accessToken = accessToken;
            this.accessTokenSecret = accessTokenSecret;
        }
    public ApiDomain() {
        }
      
        
    }
    

    TwitterDomain

        package com.twitterservice.dao;
        
        @Entity
        public class TwitterDomain implements Serializable {
        
            @Id
            @GeneratedValue(strategy = GenerationType.AUTO)
            private long id;
            private String twitteruser;
            private String twittertext;
            private String status;
        
            public String getTwitteruser() {
                return twitteruser;
            }
        
            public void setTwitteruser(String twitteruser) {
                this.twitteruser = twitteruser;
            }
        
            public String getTwittertext() {
                return twittertext;
            }
        
            public void setTwittertext(String twittertext) {
                this.twittertext = twittertext;
            }
        
            public String getStatus() {
                return status;
            }
        
            public void setStatus(String status) {
                this.status = status;
            }
        
            public TwitterDomain(String twitteruser, String twittertext, String status) {
                
                this.twitteruser = twitteruser;
                this.twittertext = twittertext;
                this.status = status;
            }
        
            public TwitterDomain() {
            }
            
        
    
    }
    

    myrepository

     package com.twitterservice.repository;
    
    
    import org.springframework.data.repository.CrudRepository;
    
    public interface TwitterRepository extends CrudRepository<TwitterDomain, Long> {
    
        List<TwitterDomain> findByTwittertext(String twittertext);
    }
    

    And error when I call to service

    java.lang.NullPointerException: null
    at com.twitterservice.service.ApiRestService.getAll(ApiRestService.java:71)
    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:497)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    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.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    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:967)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
    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.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    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.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:668)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
    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)
    

    handle to error this row

     TwitRepo.save(new TwitterDomain(a.getUser().getName(), a.getText(), "stable"));