your programing

Spring Data MongoDB의 List 매개 변수를 사용한 리포지토리 쿼리

lovepro 2023. 5. 22. 22:55
반응형

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태그 목록을 포함합니다.다음을 시도해 보았습니다.

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

하지만 이것은 오직 다음과 같은 경우에만 작동합니다.ListMongo의 질문에 할당된 태그 목록과 완전히 일치합니다.예: 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서블릿 컨테이너에 전혀 배포할 수 없습니다. (이 경우 다음 오류가 발생합니다.)

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/ #compository-messages-messages

위에서 설명한 사용 사례에 대해 다음 구현이 작동합니다.

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

CONTINING 키워드는 다음과 같이 사용할 수도 있습니다.

@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

언급URL : https://stackoverflow.com/questions/30123810/repository-query-with-a-list-parameter-in-spring-data-mongodb

반응형