Spring Data JPA Repository的findAll()方法出现空指针异常

3

我有一个 Spring-Boot API,其中包含以下端点。在 Spring Data JPA 的 findAll 查询中,它会抛出空指针异常;当我注释掉这行代码时,就没有错误了。看起来我从仓库查询中得到了一个空结果,但是通过直接查询数据库,我知道数据是存在的。我不明白为什么我会在topicsLookup变量中得到一个空值... 有人能指导我吗?

资源:

@RequestMapping(value = "/lectures/{lectureId}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, SpeakerTopicLectures> getLecture(@PathVariable Long lectureId){

        Long requestReceived = new Date().getTime();
        Map<String, SpeakerTopicLectures> result = new HashMap<>();

        log.debug("** GET Request to getLecture");
        log.debug("Querying results");

        List<SpeakerTopicLectures> dataRows = speakerTopicLecturesRepository.findBySpeakerTopicLecturesPk_LectureId(lectureId);

        // This line throws the error
        List<SpeakerTopic> topicsLookup = speakerTopicsRepository.findAll();

        // Do stuff here...

        log.debug("Got {} rows", dataRows.size());
        log.debug("Request took {}ms **", (new Date().getTime() - requestReceived));

        // wrap lecture in map object
        result.put("content", dataRows.get(0));

        return result;
}

Java Bean:

@Entity
@Table(name = "speaker_topics")
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class SpeakerTopic implements Serializable {

    @Id
    @Column(name = "topic_id")
    private Long topicId;

    @Column(name = "topic_nm")
    private String topicName;

    @Column(name = "topic_desc")
    private String topicDesc;

    @Column(name = "topic_acm_relt_rsce")
    private String relatedResources;

}

代码仓库:

import org.acm.dl.api.domain.SpeakerTopic;
import org.springframework.data.jpa.repository.JpaRepository;

public interface SpeakerTopicsRepository extends JpaRepository<SpeakerTopic,Long> {

}

如果需要更多的信息有助于理解,请告诉我,我会尽力提供。 - littlewolf
3
一个堆栈跟踪可能会有所帮助。您能否确认 speakerTopicsRepository 本身不为 null - 您是否已经使用 @Autowired 进行了注入? - NickJ
@NickJ 那就是了。我忘记了 @Inject 注解。请随意发布为答案,我会标记它。 - littlewolf
4个回答

7
最有可能的原因是speakerTopicsRepository本身为空,这可能是由于忘记自动装配它引起的,例如:
public class YourController {

  @Autowired private SpeakerTopicsRepository speakerTopicsRepository;

  @RequestMapping(value = "/lectures/{lectureId}",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
  public Map<String, SpeakerTopicLectures> getLecture(@PathVariable Long lectureId) {
     // your method...
  }

}

2

你的控制器中没有自动装配存储库。


1
尝试使用。
@Repository
@Transactional
public interface SpeakerTopicsRepository extends JpaRepository<SpeakerTopic,Long> {
    // Your Repository Code 
}

我认为缺少@Repository@Transactional。请使用它们。


请花点时间阅读编辑帮助中的内容。在Stack Overflow上的格式与其他网站不同。 - Dharman

1

对于我来说,缺少了 @Autowired。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接