Spring Data JPA Repository findAll()Null指针

时间:2017-07-26 17:02:08

标签: java hibernate spring-boot spring-data-jpa

我有一个带有端点的Spring-Boot API。它在Spring Data JPA findAll查询中抛出Null Pointer Exception;当我注释掉这一行时,我没有错误。我似乎从存储库查询中获得了null结果,但我知道数据是直接查询数据库的。我无法理解为什么我为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> {

}

4 个答案:

答案 0 :(得分:1)

最可能的原因是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...
  }

}

答案 1 :(得分:1)

存储库未自动连接到您的控制器中。

答案 2 :(得分:0)

尝试使用

@Repository
@Transactional
public interface SpeakerTopicsRepository extends JpaRepository<SpeakerTopic,Long> {
    // Your Repository Code 
}

我认为@Repository@Transactional丢失了。请使用它。

答案 3 :(得分:0)

它对我来说@Autowired不见了。