在Spring Data MongoDB中使用List参数进行存储库查询 [英] Repository query with a List parameter in Spring Data MongoDB

查看:833
本文介绍了在Spring Data MongoDB中使用List参数进行存储库查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下POJO.

@Document(collection = "questions")
public class Question {

    @Id
    private String id;

    public List<String> getTags() {
        return tags;
    }

    public void setTags(List<String> tags) {
        this.tags = tags;
    }
}

我正在尝试实现一个MongoRepository查询,该查询查找包含标签列表的所有Question.我尝试了以下方法:

I am trying to implement a MongoRepository query which finds all Questions that contain a list of tags. I have tried the following:

@Repository
public interface QuestionRepository extends MongoRepository<Question, String> {
    List<Question> findByTags(List<String> tags);
}

,但这仅在我传递给该方法的标签的List与Mongo中分配给该问题的标签的列表完全匹配时才有效.例如.如果我在Mongo中有一个带有标签[ "t1", "t2", "t3" ]的列表的问题,则当我将[ "t1", "t2" ]传递给该方法时,findByTags(List)不会返回该问题.

but this is only working when the List of tags that I'm passing to the method fully matches the list of tags assigned to the question in Mongo. E.g. if I have a question in Mongo with a list of tags [ "t1", "t2", "t3" ] it is not returned by findByTags(List) when I pass [ "t1", "t2" ] to the method.

我也尝试了以下方法:

@Repository
public interface QuestionRepository extends MongoRepository<Question, String> {
    @Query("{ tags: { $all: ?0 } }")
    List<Question> findByTags(List<String> tags);
}

,但是我的war根本无法部署到我的servlet容器. (在这种情况下,我收到以下错误消息:

but then my war could not be deployed to my servlet container at all. (I get the following error in that case:

The web application [backend] appears to have started a thread named [cluster-1-db:27017] but has failed to stop it. This is very likely to create a memory leak.

请问如何实施该自定义查询?

Would you please advise on how to implement that custom query?

推荐答案

我将自己回答问题,因为我自己才找到答案. Spring Data MongoDB文档中的以下部分列出了Spring用于其查询派生的所有受支持的关键字:

I will answer my own question as I have just found the answer by myself. The following section in the Spring Data MongoDB documentation lists all supported keywords that are used by Spring for its query derivation:

http://docs .spring.io/spring-data/mongodb/docs/current/reference/html/#repository-query-keywords

以下实现适用于上述用例:

The following implementation works for the use case described above:

@Repository
public interface QuestionRepository extends MongoRepository<Question, String> {
     List<Question> findByTagsIn(List<String> tags);
}

这篇关于在Spring Data MongoDB中使用List参数进行存储库查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆