我有一个 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> {
}
最可能的原因是
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...
}
}
存储库未在您的控制器中自动连接。
尝试使用
@Repository
@Transactional
public interface SpeakerTopicsRepository extends JpaRepository<SpeakerTopic,Long> {
// Your Repository Code
}
我认为
@Repository
和 @Transactional
不见了。请使用它。
我缺少@Autowired。
在控制器中使用@Autowire 解决了我的问题。