使用Spring Data MongoDB中的List参数进行存储库查询

时间:2015-05-08 12:23:46

标签: java spring mongodb

我有以下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。我尝试过以下方法:

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

但这只适用于我传递给该方法的List个标签与分配给Mongo中的问题的标签列表完全匹配的情况。例如。如果我在Mongo中有一个标记[ "t1", "t2", "t3" ]的问题,那么当我将findByTags(List)传递给该方法时,[ "t1", "t2" ]就不会返回该问题。

我也尝试了以下内容:

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

但是我的war根本无法部署到我的servlet容器中。 (在这种情况下我得到以下错误:

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.

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

2 个答案:

答案 0 :(得分:42)

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

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

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

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

答案 1 :(得分:7)

也可以使用CONTAINING关键字:

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

示例以及它的mongo查询如何:

findByAddressesContaining(Address address)

{"addresses" : { "$in" : address}}

这也可以接受参数列表。

请参阅文档:https://github.com/spring-projects/spring-data-mongodb/blob/e28bede416e4ddac19a35dc239388afc90b9cac4/src/main/asciidoc/reference/mongo-repositories.adoc

相关问题