Search code examples
spring-bootapijpanullpointerexceptionspring-repositories

NullPointerException when i try to add a object from a jpa repository to a list


I want to get all projects, where person is empty. Every time i call the endpoint a get a NullPointerException for this line emptyProjects.add(project);. Maybe its because of the JsonBackReference?

And if so, is there any way to get the list of projects where the person list is empty?

Project Class:

package com.example.api.model;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Entity
@Table(name = "project")
public class Project {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @NotNull
    private String name;

    @ManyToMany(mappedBy = "projectList")
    @JsonBackReference
    private List<Person> person;

    public Project(){}

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Person> getPerson() {
        return person;
    }

    public void setPerson(List<Person> person) {
        this.person = person;
    }
}

Method iam working on:

@GetMapping("/project/empty")
    public ResponseEntity getEmptyProjects(){
        List <Project> emptyProjects = null;
        for (int i = 0; i <= projectRepo.findAll().size(); i++){
                Project project = projectRepo.findAll().get(i);
                emptyProjects.add(project);
                if (project.getPerson().isEmpty() == true){
                    emptyProjects.add(project);
                }
        }
        return ResponseEntity.ok(emptyProjects);
    }

Thanks!


Solution

  • You're not initializing the list, so you're having a NullPointerException because you're trying to call a method on a null object. Replace this line:

    List <Project> emptyProjects = null;
    

    with this

    List <Project> emptyProjects = new ArrayList<>();
    

    Moreover, there is no need of calling the database for each iteration of the loop. It'd be better to save the result in a list List<Project> allProjects = projectRepo.findAll() and loop through this list for better performance