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

标签 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.

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

最佳答案

我会回答我自己的问题,因为我自己刚刚找到了答案。 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);
}

关于java - 在 Spring Data MongoDB 中使用 List 参数进行存储库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30123810/

相关文章:

ios - 解析注册在 Swift 3 中无法正常工作

具有 3 个子级别的 MongoDB 嵌套查找

java - 抽奖比赛练习

Java 如果我有不同的构造函数但有相同的接口(interface),我应该使用什么设计模式来实例化对象?

java - 使图像按钮的行为类似于切换按钮

java - Jface的CheckboxTreeViewer如何设置初始选择

spring - 如何保证Spring bean的顺序?属性占位符问题

spring - JavaFX + Spring(JDBC 和@SpringBootApplication 和@Autowired 和@Transactional)

javascript - 通过 mongoose 将条目插入 MongoDB 中的多级嵌套数组

java - 使用 Spring 在 Java 中创建运行时对象