Home > Blockchain >  java.lang.NullPointerException: Cannot invoke "com.example.repository.StudentRepository.save(Ob
java.lang.NullPointerException: Cannot invoke "com.example.repository.StudentRepository.save(Ob

Time:01-12

`HTTP Status 500 – Internal Server Error Type Exception Report

Message Request processing failed: java.lang.NullPointerException: Cannot invoke "com.example.repository.StudentRepository.save(Object)" because "this.studentRepository" is null

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

jakarta.servlet.ServletException: Request processing failed: java.lang.NullPointerException: Cannot invoke "com.example.repository.StudentRepository.save(Object)" because "this.studentRepository" is null org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1018) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:913) jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:884) jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) Root Cause

java.lang.NullPointerException: Cannot invoke "com.example.repository.StudentRepository.save(Object)" because "this.studentRepository" is null com.example.service.impl.StudentServiceImpl.saveStudent(StudentServiceImpl.java:37) com.example.controller.StudentController.saveStudent(StudentController.java:45) java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.base/java.lang.reflect.Method.invoke(Method.java:568) org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1010) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:913) jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:884) jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) Note The full stack trace of the root cause is available in the server logs.`

1.Controller Class

@Controller
    public class StudentController {
    
        private StudentService studentService;
        
        public StudentController(StudentService studentService) 
        {
            super();
            this.studentService = studentService;
        }
    
        @GetMapping("/students")
        public String listStudents()
        {
            //model.addAttribute("students",studentService.getAllStudent());
            return "students";
        }
        
        @GetMapping("/students/new")
        public String createStudentForm(Model model)
        {
            Student st = new Student();
            model.addAttribute("student",st);
            
            return "create_student";    
        }
            
        @PostMapping("/students")
        public String saveStudent(@ModelAttribute("student") Student student)
        {
            System.out.println("object: "   student.getFirstName() "=" student.getEmail() " = " student.getLastName());
            studentService.saveStudent(student);
            return "redirect:/students";
        }
        
        
    }


2.Entity Class

package com.example.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "students")
public class Student {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name = "first_name", nullable = false)
    private String firstName;
    
    @Column(name = "last_name")
    private String lastName;
    
    @Column(name = "email")
    private String email;
    
    public Student() {
        
    }
    
    public Student(String firstName, String lastName, String email) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

3.Student Repository Interface

    package com.example.repository;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    
    import com.example.entity.Student;
    
    public interface StudentRepository extends JpaRepository<Student, Long>{
    
    }

4. Student Service

package com.example.service;

import java.util.List;

import com.example.entity.Student;


public interface StudentService {
    List<Student> getAllStudents();
    
    Student saveStudent(Student student);
    
    Student getStudentById(Long id);
    
    Student updateStudent(Student student);
    
    void deleteStudentById(Long id);
}
4. Student Service Implementation

    package com.example.service.impl;
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.example.entity.Student;
    import com.example.repository.StudentRepository;
    import com.example.service.StudentService;
    
    
    @Service
    public class StudentServiceImpl implements StudentService{
    
        
        private StudentRepository studentRepository;
    
        public StudentServiceImpl() {
        super();
        }
    
        //@Autowired
        public StudentServiceImpl(StudentRepository studentRepository) {
            super();
            System.out.println("Student Repo:= " this.studentRepository);
            this.studentRepository = studentRepository;
        }
    
        @Override
        public List<Student> getAllStudents() {
            return studentRepository.findAll();
        }
    
        @Override
        public Student saveStudent(Student student) {
            return studentRepository.save(student);
        }
    
        @Override
        public Student getStudentById(Long id) {
            return studentRepository.findById(id).get();
        }
    
        @Override
        public Student updateStudent(Student student) {
            return studentRepository.save(student);  //.save(student);
        }
    
        @Override
        public void deleteStudentById(Long id) {
            studentRepository.deleteById(id);   
        }
    
    }

CodePudding user response:

Use @RequestBody instead of @ModelAttribute in controller save method.

@PostMapping("/students")
    public String saveStudent(@RequestBody Student student)
    {
        System.out.println("object: "   student.getFirstName() "=" student.getEmail() " = " student.getLastName());
        studentService.saveStudent(student);
        return "redirect:/students";
    }

CodePudding user response:

The error you are getting says that the studentRepository is null. This is because you have not autowired the studentRepository field or the constructor in the Student Service Implementation class. Try using the @Autowired on the private StudentRepository studentRepository; field or on the Constructor method of the Student Service Implementation. Try this

4. Student Service Implementation

package com.example.service.impl;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.entity.Student;
import com.example.repository.StudentRepository;
import com.example.service.StudentService;


@Service
public class StudentServiceImpl implements StudentService{

    
    private StudentRepository studentRepository;

    public StudentServiceImpl() {
    super();
    }

    @Autowired
    public StudentServiceImpl(StudentRepository studentRepository) {
        super();
        System.out.println("Student Repo:= " this.studentRepository);
        this.studentRepository = studentRepository;
    }

    @Override
    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    @Override
    public Student saveStudent(Student student) {
        return studentRepository.save(student);
    }

    @Override
    public Student getStudentById(Long id) {
        return studentRepository.findById(id).get();
    }

    @Override
    public Student updateStudent(Student student) {
        return studentRepository.save(student);  //.save(student);
    }

    @Override
    public void deleteStudentById(Long id) {
        studentRepository.deleteById(id);   
    }

}

or

4. Student Service Implementation

package com.example.service.impl;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.entity.Student;
import com.example.repository.StudentRepository;
import com.example.service.StudentService;


@Service
public class StudentServiceImpl implements StudentService{

    @Autowired
    private StudentRepository studentRepository;

    public StudentServiceImpl() {
    super();
    }

    public StudentServiceImpl(StudentRepository studentRepository) {
        super();
        System.out.println("Student Repo:= " this.studentRepository);
        this.studentRepository = studentRepository;
    }

    @Override
    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    @Override
    public Student saveStudent(Student student) {
        return studentRepository.save(student);
    }

    @Override
    public Student getStudentById(Long id) {
        return studentRepository.findById(id).get();
    }

    @Override
    public Student updateStudent(Student student) {
        return studentRepository.save(student);  //.save(student);
    }

    @Override
    public void deleteStudentById(Long id) {
        studentRepository.deleteById(id);   
    }

}

Let me know if you face any more issues.

  • Related