0

I am a newbie to spring, when I am trying to save an entity to the database it is throwing a null pointer exception. Here is the relevant code for reference:-

Here is the controller:-

import com.project.newsblog.entities.Post;
import com.project.newsblog.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @Autowired
    public PostService postService;


    @PostMapping(value = "/post")
    public String post(@RequestBody Post item){
        System.out.println(item.toString());
        postService.post(item);
        return "Successful";
    }

}

Here is the service Service(root cause of the eror):-

import com.project.newsblog.entities.Post;
import com.project.newsblog.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostService {

    private PostRepository postRepository;

    public List<Post> getAllPost(){
        return postRepository.findAll();
    }
    public void post(Post post){
        postRepository.save(post);
    }
}

Here is the Entity for reference:-

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDateTime;

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String creator;
    private  String title;
    private String text;
    private LocalDateTime dateTime;

    public Post() {
    }

    @Override
    public String toString() {
        return "Post{" +
                "id=" + id +
                ", creator='" + creator + '\'' +
                ", title='" + title + '\'' +
                ", text='" + text + '\'' +
                ", dateTime=" + dateTime +
                '}';
    }

    public Post(String creator, String title, String text) {
        this.creator = creator;
        this.title = title;
        this.text = text;
        this.dateTime = LocalDateTime.now();
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getCreator() {
        return creator;
    }

    public void setCreator(String creator) {
        this.creator = creator;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public LocalDateTime getDateTime() {
        return dateTime;
    }

    public void setDateTime(LocalDateTime dateTime) {
        this.dateTime = dateTime;
    }
}

There seems to be a problem while saving the json payload to database. I think I am missing something which I am not able to figure out. Please help me out. Here's the most relevent debug message:-

Post{id=1, creator='Someone', title='This is the title', text='This is the title', dateTime=null}
2021-06-15 22:52:22.145 DEBUG 14756 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet        : Failed to complete request: java.lang.NullPointerException
2021-06-15 22:52:22.146 ERROR 14756 --- [nio-8080-exec-8] 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 com.project.newsblog.service.PostService.post(PostService.java:20) ~[classes/:na]
    at com.project.newsblog.controller.MyController.post(MyController.java:21) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]

Edit:- When I am annotating PostRepository line in service part with @Autowired, it is giving the error: "No qualifying bean of type 'com.project.newsblog.repository.PostRepository'". Here is the repository code:-

package com.project.newsblog.repository;

import com.project.newsblog.entities.Post;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
}

3 Answers 3

2

It is clearly due to the fact your

postRepository is not autowired. Spring cannot intantiate it by itself until you specify it with an annotation @Autowired, or personally instantiate it say in a @PostConstruct way.

Have a new Interface

public interface PostRepository extends JpaRepository<Post , Long>{

}

And in your sevice class.

@AutoWired
private PostRepository postRepository;

Have your packages like this. All packages should be within the directory of SpringBootApp package.

enter image description here

Hope this helps !!

Sign up to request clarification or add additional context in comments.

1 Comment

Make sure you are having proper packaging structure.
0

You haven't initialized the postRepository in your PostService. Did you mean for it to be autowired?

1 Comment

Yes, It was meant to be autowired. But after using @Autowired it says ''Consider defining a bean of type 'com.project.newsblog.repository.PostRepository' in your configuration.'' what's the problem this time Sir. PostRepository is simple interface that is extending JpaRepository.
0

I guess, you had missed to annotate as @Autowired to the inject bean in service class

@Autowired private PostRepository postRepository;

3 Comments

Yes, that is true for sure but when I am annotating it, it is giving another error, ie. No qualifying bean of type 'com.project.newsblog.repository.PostRepository. I have edited the question for more clarity.
Is your repository class exists in same package or different package?
If its in different package then you have to declare @ComponentScan(basePackages = "com.project.newsblog.*") at main springbootapplication class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.