2017-07-26 1247 views
0

我有一個Spring-Boot API,帶有下面的端點。它在Spring Data JPA findAll查詢中拋出一個空指針異常;當我評論這一行時,我沒有任何錯誤。看來,我從存儲庫查詢中得到一個空結果,但我知道直接從數據庫查詢數據。我不明白爲什麼我得到一個空的topicsLookup變量...任何人都可以指出我在正確的方向嗎?Spring Data JPA Repository findAll()空指針

資源:

@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> { 

} 
+0

如果有更多信息會有幫助,請告訴我,我會盡量提供。 – littlewolf

+2

堆棧跟蹤可能會有所幫助。你能確認speakerTopicsRepository本身是否爲空 - 你有@Autowired嗎? – NickJ

+0

@NickJ就是這樣。我忘了'@ Inject'註釋。隨意發佈作爲答案,我會標記它。 – littlewolf

回答

1

最有可能的CA使用的是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... 
    } 

}