복붙노트

[SPRING] 사용자 정의 컬렉션 이름을 가진 Spring 데이터 MongoDB 저장소

SPRING

사용자 정의 컬렉션 이름을 가진 Spring 데이터 MongoDB 저장소

MongoDB 용 Spring Data를 사용하고 있으며 런타임시 컬렉션을 구성 할 수 있어야합니다.

내 저장소는 다음과 같이 정의됩니다.

@Repository
public interface EventDataRepository extends MongoRepository<EventData, String> {
}

나는이 바보 같은 예를 시도했다.

@Document(collection = "${mongo.event.collection}")
public class EventData implements Serializable {

하지만 mongo.event.collection은 @Value 주석과 마찬가지로 이름으로 해석되지 않았습니다.

조금 더 디버깅 및 검색하고 다음을 시도 :     @Document (collection = "# {$ {mongo.event.collection}}")

이로 인해 예외가 발생했습니다.

Caused by: org.springframework.expression.spel.SpelParseException: EL1041E:(pos 1): After parsing a valid expression, there is still more data in the expression: 'lcurly({)'
    at org.springframework.expression.spel.standard.InternalSpelExpressionParser.doParseExpression(InternalSpelExpressionParser.java:129)
    at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:60)
    at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:32)
    at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpressions(TemplateAwareExpressionParser.java:154)
    at org.springframework.expression.common.TemplateAwareExpressionParser.parseTemplate(TemplateAwareExpressionParser.java:85)

아마도 스프링의 Property Configurer에서 값을 액세스하는 데 Spel을 사용하는 방법을 모르겠다.

코드를 단계별로 살펴보면 컬렉션 이름이나 표현식을 지정하는 방법이 있다는 것을 알았지 만 어떤 목적을 위해이 주석을 사용해야하는지 또는 어떻게해야하는지 잘 모르겠습니다.

고마워. - 너 ~

해결법

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

    1.결국, 여기에 트릭을 한 작업이 있습니다. SPeL 표현식을 사용하여 Spring Properties Configurer에서 데이터에 액세스하는 방법을 실제로 알지 못한다고 생각합니다.

    결국, 여기에 트릭을 한 작업이 있습니다. SPeL 표현식을 사용하여 Spring Properties Configurer에서 데이터에 액세스하는 방법을 실제로 알지 못한다고 생각합니다.

    내 @Configuration 클래스에서 :

    @Value("${mongo.event.collection}")
    private String
        mongoEventCollectionName;
    
    @Bean
    public String mongoEventCollectionName() {
        return
            mongoEventCollectionName;
    }
    

    내 문서에 :

    @Document(collection = "#{mongoEventCollectionName}")
    

    이것은 제대로 작동하고 내 .properties 파일에 구성된 이름을 올바르게 선택하는 것처럼 보입니다. 그러나 @Value 주석에서와 같이 왜 $로 값에 액세스 할 수 없는지 아직 확실하지 않습니다.

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

    2.엔티티 클래스 정의

    엔티티 클래스 정의

    @Document(collection = "${EventDataRepository.getCollectionName()}")
    public class EventData implements Serializable {
    

    "collectionName"에 대한 getter 및 setter 메소드를 사용하여 사용자 정의 저장소 인터페이스를 정의하십시오.

    public interface EventDataRepositoryCustom {
    
        String getCollectionName();
    
        void setCollectionName(String collectionName);
    }
    

    "collectionName"구현을 사용하여 사용자 정의 저장소의 구현 클래스를 제공합니다.

    public class EventDataRepositoryImpl implements EventDataRepositoryCustom{
    
        private static String collectionName = "myCollection";
    
        @Override
        public String getCollectionName() {
            return collectionName;
        }
    
        @Override
        public void setCollectionName(String collectionName) {
            this.collectionName = collectionName;
        }
    }
    

    다음과 같이 저장소 인터페이스의 확장 목록에 EventDataRepositoryImpl을 추가하십시오.

    @Repository
    public interface EventDataRepository extends MongoRepository<EventData, String>, EventDataRepositoryImpl  {
    }
    

    이제 MongoRepository를 사용하는 Service 클래스에서 컬렉션 이름을 설정하면

    @Autowired
    EventDataRepository  repository ;
    
    repository.setCollectionName("collectionName");
    
  3. ==============================

    3.엔티티 클래스

    엔티티 클래스

    @Document    // remove the parameters from here
    
    
    public class EscalationCase 
    {
    
    }
    

    구성 클래스

    public class MongoDBConfiguration {
    
        private final Logger logger = LoggerFactory.getLogger(MongoDBConfiguration.class);
    
        @Value("${sfdc.mongodb.collection}") //taking collection name from properties file 
        private String collectionName;
    
        @Bean
    
        public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MongoMappingContext context) {
    
            MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory), context);
            converter.setTypeMapper(new DefaultMongoTypeMapper(null));
            MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);
            if (!mongoTemplate.collectionExists(collectionName)) {
                mongoTemplate.createCollection(collectionName);  // adding the collection name here
            }
            return mongoTemplate;
    
        }
    }
    
  4. ==============================

    4.SPeL 만 사용하면이 문제를 해결할 수 있습니다.

    SPeL 만 사용하면이 문제를 해결할 수 있습니다.

    @Document(collection = "#{environment.getProperty('mongo.event.collection')}")
    public class EventData implements Serializable {
        ...
    }
    

    Spring 5.x 업데이트 :

    Spring 5.x 이후 환경을 만들기 위해서는 @를 추가로 필요로합니다 :

    @Document(collection = "#{@environment.getProperty('mongo.event.collection')}")
    public class EventData implements Serializable {
        ...
    }
    
  5. from https://stackoverflow.com/questions/29597482/spring-data-mongodb-repository-with-custom-collection-name by cc-by-sa and MIT license