我有一个Spring-Boot API,端点如下。它在 Spring 数据 JPAfindAll
查询上抛出空指针异常;当我注释掉这一行时,我没有收到任何错误。似乎我从存储库查询中获得了空结果,但我知道数据来自直接查询数据库。我不明白为什么我得到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
本身为 null,这可能是由于忘记自动连线引起的,例如
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。