Vishal
Vishal

Reputation: 724

How to specify collection name while using spring data mongo repository?

I am using spring data to fetch data for my application.

The repository class uses a mongo entity class which is being added as an upstream dependency to my project which means I don't have any control to change the source code of the class. As a result of this, I cannot use @Document annotation from org.springframework.data.mongodb.core.mapping to my mongo entity class.

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface DummyRepository extends MongoRepository<Dummy, String> {

    Page<Dummy> findAll(Pageable pageable);

}

Here, I don't have any control over source code of Dummy class so I can't add @Document to specify collection name for this class

How can I specify the collection name while using DummyRepository to query mongo collection?

Upvotes: 1

Views: 1239

Answers (1)

Christoph Strobl
Christoph Strobl

Reputation: 6736

One way would be to use @EnableMongoRepositories#repositoryFactoryBeanClass with your own flavor of MongoRepsoitoryFactoryBean overriding getEntityInformation(Class).
Unfortunately there's a bug (DATAMONGO-2297) in the code and for the time being you also need to customize getTargetRepsoitory(RepositoryInformation) as shown in the snippet below.

@Configuration
@EnableMongoRepositories(repositoryFactoryBeanClass = CustomRepoFactory.class)
class config extends AbstractMongoConfiguration {
  // ...
}

class CustomRepoFactory extends MongoRepositoryFactoryBean {

  public CustomRepoFactory(Class repositoryInterface) {
    super(repositoryInterface);
  }

  @Override
  protected RepositoryFactorySupport getFactoryInstance(MongoOperations operations) {

    return new MongoRepositoryFactory(operations) {

      @Override
      public <T, ID> MongoEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {

       return new MappingMongoEntityInformation(
            operations.getConverter().getMappingContext().getPersistentEntity(domainClass)) {

          @Override
          public String getCollectionName() {
            return "customize-as-you-wish";
          }
        };
      }

      @Override // you should not need this when DATAMONGO-2297 is resolved
      protected Object getTargetRepository(RepositoryInformation information) {

        MongoEntityInformation<?, Serializable> entityInformation = getEntityInformation(information.getDomainType());
        return getTargetRepositoryViaReflection(information, entityInformation, operations);
      }
    };
  }
}

Upvotes: 2

Related Questions