복붙노트

[SPRING] Spring Data Mongodb - 다른 유형의 콜렉션을위한 저장소

SPRING

Spring Data Mongodb - 다른 유형의 콜렉션을위한 저장소

Java 형식에 매핑하는 엔티티의 세 가지 유형이 포함될 수있는 mongo 컬렉션이 있습니다.

컬렉션은 상위 항목에 자식 노드의 dbRef를 사용하여 트리 구조를 저장하는 작업입니다.

Spring 참조 문서의 주제에 대한 정보를 찾지 못했기 때문에 여기에서 묻습니다. 다른 유형의 객체를 포함 할 수있는 컬렉션을 사용하기 위해 저장소 메커니즘을 사용하는 방법이 있습니까?

하나의 컬렉션에서 여러 유형의 여러 저장소를 선언하는 것은별로 좋지 않은 것처럼 보입니다. 쿼리 된 개체가 예상되는 유형이 아니며 가능한 모든 유형의 inherrit가 작동하지 않는 추상 클래스 저장소를 만드는 경우에 항상 투쟁하기 때문입니다.

내가 의미하는 것을 설명하기 위해 :

/**
 * This seems not safe
 */
public interface NodeRepository extends MongoRepository<Node, String> { }
public interface LeafType1Repository extends MongoRepository<LeafType1, String> { }
public interface LeafType2Repository extends MongoRepository<LeafType2, String> { }

/**
 * This doesn't work at all
 */
public interface MyCollectionRepository extends MongoRepository<AbstractMyCollectionNode, String> { }

해결법

  1. ==============================

    1.Node \ LeafType1 \ LeafType2가 AbstractMyCollectionNode의 하위 클래스 인 경우 작업이 쉽습니다. 다음과 같이 작성한 저장소를 선언하십시오.

    Node \ LeafType1 \ LeafType2가 AbstractMyCollectionNode의 하위 클래스 인 경우 작업이 쉽습니다. 다음과 같이 작성한 저장소를 선언하십시오.

    public interface MyCollectionRepository extends MongoRepository<AbstractMyCollectionNode, String> { }
    

    우리는 프로젝트에서이 작업을 수행했으며 좋은 결과를 얻었습니다. Spring Data는 '_class'라는 속성을 mongodb 컬렉션의 문서에 추가하여 인스턴스화 할 클래스를 찾아 낼 수 있습니다.

    하나의 컬렉션에 저장된 문서는 약간의 유사성을 가질 수 있습니다. 아마도 제네릭 클래스를 추출 할 수 있습니다.

    다음은 우리 프로젝트 중 하나에서 복사 한 코드입니다.

    실재:

    public abstract class Document {
        private String id;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
        ....
    
    public class WebClipDocument extends Document {
        private String digest;
        ...
    

    저장소:

    public interface DocumentDao extends MongoRepository<Document, String>{
    ...
    

    그리고 mongodb 콜렉션의 문서에 "_class"속성이없는 경우. 당신은 변환기를 사용할 수 있습니다 :

  2. ==============================

    2.Spring 데이터는 엔티티 클래스를 찾을 때 Entity-Repository-Declarations를 엔트리 포인트로 사용한다 (엔티티의 패키지를 직접 스캔하지는 않는다).

    Spring 데이터는 엔티티 클래스를 찾을 때 Entity-Repository-Declarations를 엔트리 포인트로 사용한다 (엔티티의 패키지를 직접 스캔하지는 않는다).

    따라서 OP에서 "안전하지 않은"것으로 제안한 것처럼 하위 클래스에 대한 "사용되지 않는"Repository-Interface를 선언하면됩니다.

    public interface NodeRepository extends MongoRepository<Node, String> { 
      // all of your repo methods go here
      Node findById(String id);
      Node findFirst100ByNodeType(String nodeType);
      ... etc.
    }
    public interface LeafType1Repository extends MongoRepository<LeafType1, String> {
      // leave empty
    }
    public interface LeafType2Repository extends MongoRepository<LeafType2, String> { 
      // leave empty
    }
    

    추가 LeafTypeX 저장소를 사용할 필요가 없으며 LeafType1 및 LeafType2 유형의 개체를 저장하고 찾는 데 NodeRepository를 사용할 수 있습니다. 그러나 다른 두 저장소의 선언이 필요하므로 LeafType1과 LeafType2는 초기 스캔이 수행 될 때 엔티티로 발견됩니다.

    추신 :이 모든 것은 물론 LeafType1과 LeafType2 클래스에 @Document (collection = "nodes") 주석이 있다고 가정합니다.

  3. from https://stackoverflow.com/questions/27246274/spring-data-mongodb-repository-for-collection-with-different-types by cc-by-sa and MIT license