【问题标题】:Repository query with a List parameter in Spring Data MongoDB在 Spring Data MongoDB 中使用 List 参数进行存储库查询
【发布时间】:2015-07-19 08:50:39
【问题描述】:

我有以下 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 查询,它可以找到所有包含标签列表的Questions。我尝试了以下方法:

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

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

我也尝试了以下方法:

@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.

您能否就如何实现该自定义查询提出建议?

【问题讨论】:

    标签: java spring mongodb


    【解决方案1】:

    我会回答我自己的问题,因为我自己刚刚找到了答案。 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 个标签的问题怎么办?不知道标签?
    • 知道了!! @Query("{tags: {$exists:true}, $where:'this.tags.length > 0'}")
    • 感谢@Marchev,您的回答对我帮助很大。我为此苦苦挣扎了一段时间,但感谢一切都很好。
    • @AdrianGrzywaczewski 我很高兴它有帮助:)
    【解决方案2】:

    也可以使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 2014-09-11
      相关资源
      最近更新 更多