首页 > 解决方案 > 我正在尝试使用 spring boot 执行一个简单的 crud 操作 findall(),它没有任何错误或警告,但给出了 NULL 异常

问题描述

这是 TopicService.java 的一部分

我在这一行得到一个 NULL 指针异常 TopicRepo.findAll().forEach(topics::add);

私有主题Repo TopicRepo;这是我自动连接依赖项的地方

package io.javabrains.example.topic;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Service
public class TopicService {// creating a business service

    @Autowired
    private topicRepo TopicRepo; // whenever the TopicService creates an instance then the instance of topicRepo will be injectjed in the variable

    private ArrayList<Topic> topics = new ArrayList<>(Arrays.asList(
                new Topic("spring1", "nishhcal", "name"),
                new Topic("spring2", "nishhca2", "name2"),
                new Topic("spring3", "nishhca3", "name3")));



    public List<Topic> getAllTopics(){

//        return topics;
        List<Topic> topics = new ArrayList<>();
        TopicRepo.findAll().forEach(topics::add);
        return topics;
    }

    public Topic getSpecificTopic(String id){
//        for (int r=0; r < topics.size(); r++){
//
//            if((topics.get(r).getId()).equals(id)){
//
//                return topics.get(r);
//            }
//        }
//        return topics.stream().filter(t -> t.getId().equals(id)).findFirst().get();// alternative way of doing it
        return topics.get(0);
    }

    public void addTopic(Topic topic){
//        topics.add(topic);
        TopicRepo.save(topic);

    }

topicRepo.java,这是我扩展 crud 存储库的地方

package io.javabrains.example.topic;

import org.springframework.data.repository.CrudRepository;

public interface topicRepo extends CrudRepository<Topic, String> {

}

这就是我的 application.properties 文件中的内容

#JPA
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=default
spring.jpa.show-sql=true

这是我的 Topic.java 的一部分

package io.javabrains.example.topic;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Topic {

    @Id
    private String id;
    private String name;
    private String description;


    public Topic() {

    }

标签: javaspringspring-bootspring-mvccrud-repository

解决方案


Topic 类是否用 JPA @Entity 注释并且在 String 字段上有 @Id ?注意:尝试以大写格式声明类/接口名称。


推荐阅读