如何解决我正在尝试使用 spring boot 执行简单的 crud 操作 findall(),它符合要求而没有任何错误或警告,但给出一个 NULL 异常
这是 TopicService.java 的一部分
我在这一行得到一个 NULL 指针异常 TopicRepo.findAll().forEach(topics::add);
私有topicRepo 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 ? 注意:尽量以大写格式声明类/接口名称。
,在你的topicRepo接口中添加@Repository注解:
@Repository
public interface topicRepo extends CrudRepository<Topic,String> {
,
如果我没记错的话,您仍然需要在@Repository 文件中创建您需要的函数/方法,如下面来自docs 的示例。也尽量保持类的语法以大写字母 TopicRepo 而不是 topicRepo 和小写的 topicReport 而不是 TopicRepo 的对象开头:
@Autowired
TopicRepo topicReport
最后是你的回购界面:
@Repository
public interface TopicRepo extends CrudRepository<Topic,Long> {
List<Topic> findAll();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。