簡體   English   中英

Spring 數據 - MongoRepository - @Query 以在嵌套對象列表中查找項目

[英]Spring Data - MongoRepository - @Query to find item within nested list of objects

我正在嘗試查詢 MongoDB 以返回問題文檔 object 中包含的單個答案 object。

我正在使用 Spring、MongoRepository 和 JDK 11。

我的問題文檔 POJO:

@Data
@Document(collection = "Questions")
@AllArgsConstructor(onConstructor = @__(@Autowired))
@NoArgsConstructor
     public class QuestionDocument {
     @Id
     private String questionId;
     (...) 
     private List<Answer> answers;
     (...)
}

我的答案POJO:

@Data
public class Answer implements Serializable {
     private String answerId;
     (...)

我的問題庫:

@Repository
public interface QuestionRepository extends MongoRepository<QuestionDocument, String> {
     @Query(value = "{ { 'questionId' : ?0 }, { 'answers.$answerId' : ?1 } }")
     Answer findByQuestionIdAndAnswerId(String questionId, String answerId);

我的問題服務實現:

public getAnswer(String questionId, String answerId){
     Answer answer = findByQuestionIdAndAnswerId(questionId, answerId);
     return answer;
}

protected Answer findByQuestionIdAndAnswerId(String questionId, String answerId){
     Answer answer;
     try {
     answer = questionRepository.findByQuestionIdAndAnswerId(questionId, answerId);
     } catch (Exception e) {
     throw new IllegalArgumentException("There is no answer with this ID.");
}
     return answer;
}

當我到達 Postman 中的端點時,會出現正確的響應正文,但它的所有值都是 null。我已驗證我的參數中傳遞了正確的 questionId 和 answerId。

我還查閱了其他幾個 SO 帖子以及 Spring 和 MongoDB 文檔,但到目前為止,實現我所閱讀的關於按屬性遍歷嵌套對象的內容並沒有幫助。

我的@Query 值需要如何更改才能從這個嵌套的答案列表中正確返回特定的答案 object?

我試圖創建 findBy 方法,例如: findByQuestion_Answers_AnswerId(String answerId);

我試圖在我的List<Answer> answers上方添加@DBRef ,並在private String answerId;上方添加@Document(collection = "Answers")@Id ; 在我的答案 POJO 中。 然后清空數據庫,新建問答,查詢具體的answerId,還是返回了null的數據。

我期望的是,給定 questionId 和 answerId,查詢將返回一個 Answer object 及其相關信息(answerBody、answerAuthor 等)。

我的 postman 響應狀態為 SUCCESS,但數據是 null。

您可以將查詢更改為此。

@Query(value = "{{'questionId' : ?0, 'answers.answerId' : ?1}}")

或者,只需定義此方法。

findByQuestionIdAndAnswerId(String questionId, String answerId);

返回類型將是QuestionDocument ,而不是Answer

更多細節在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM