java - 我正在尝试使用 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() {
}
解决方案
Topic 类是否用 JPA @Entity 注释并且在 String 字段上有 @Id ?注意:尝试以大写格式声明类/接口名称。
推荐阅读
- javascript - PayPal 无法完成交易
- javascript - 使用 JavaScript 删除网站上所有客户端存储的数据
- python - ValueError:DataFrame 构造函数未正确调用- 拟合 SparsePCA 后
- python - 如何在pygame中使用两个输入获得正确的逻辑真值表结果,而不必在正确的时间按下两个输入
- javascript - React-google-chart 引发内容安全策略问题
- cordova - 科尔多瓦 ios 6.0.0 不显示启动画面图像
- aframe - 有没有办法在 A-Frame 项目中包含人脸跟踪?
- r - 如何在 R 中制作分组条形图?
- bash - 重击:使用 || 和 && 一起
- python - python程序中的目标路径