在通过嵌套类的LIST的Id进行搜索时,PagingAndSortingRepository不起作用

时间:2016-12-26 18:57:56

标签: mongodb spring-boot

我在Mongodb上使用PagingAndSortingRepository。 我的模型类如下:

public class Question {

    @Id
    private String id;
    private List<Answer> answers;
//Other attributes
}

public class Answer {
    @Id
    private String id;
//Other attributes
}

我的存储库如下:

public interface QuestionRepository extends PagingAndSortingRepository<Question, String> {
    public List<Question> findByAnswersIdIn(List<String> answerIds);

}

由于某种原因,结果是空记录,即使它们确实存在。

处理嵌套类的List时语法是否不同?

样本文件:

{
    "id": "58609cd88ba6bc24589a7850",
    "mainQuestion": "Does this camera have built in wifi for photos transfer?",
    "answers": [
      {
        "id": "586153458ba6bc22f8b7c4a1",
        "mainAnswer": "Yes, it has wifi.",
        "author": {
          "id": "586153468ba6bc22f8b7c4a2",
          "appUserId": "5851e7768ba6bc0dc0f288a6",          
        },       
        "verifiedAnswer": false
      },
      {
        "id": "58616aed8ba6bc0c0c111d31",
        "mainAnswer": "Yes, they do have wifi",
        "author": {
          "id": "58616aee8ba6bc0c0c111d32",
          "appUserId": "5851e7768ba6bc0dc0f288a6",         
        },        
        "verifiedAnswer": false
      }
    ],
    "topic": "Nikon d5500",
    "tags": null
  }

2 个答案:

答案 0 :(得分:0)

在我看来,你的方法应该是这样的:

public List<Question> findByAnswersIn(List<Answer> answers);

你给Strings而不是答案。可能这是问题所在。

答案 1 :(得分:0)

看起来spring mongo db不支持嵌入文档的id注释。对于你的情况,如果你可以在嵌入文档中将你的id重命名为answerId。

将您的答案更新为以下内容。

public class Answer {
  private String answerId;
  private String mainAnswer;
}

你可以做这样的事情来保存答案中的问题。

Question question = new Question();
List<Answer> answers = new ArrayList<Answer>();
Answer answer = new Answer();
answer.setAnswerId(new ObjectId().toString());
answer.setMainAnswer("Yes, it has wifi.");
answers.add(answer);
question.setAnswers(answers);
questionRepository.save(question);

现在你可以做这样的事情来用问题ID查询问题。

List<Question> question = 
 questionRepository.findByAnswersAnswerIdIn(Arrays.asList("586153458ba6bc22f8b7c4a1"));