Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-Data: specify which MongoTemplate a MongoRepository should use

The following configuration is given:

@Configuration
public class AppConfiguration {

  @Bean
  Mongo mongo() throws UnknownHostException {
    return new Mongo("localhost");
  }

  @Bean(name = "MovieTemplate")
  MongoTemplate beagleTemplate(Mongo mongo) {
    return new MongoTemplate(mongo, "MovieDatabase");
  }

  @Bean(name = "AnotherTemplate")
  MongoTemplate tmdbTemplate(Mongo mongo) {
    return new MongoTemplate(mongo, "AnotherDatabase");
  }
}

I need a repository to access movies, which looks kinda like this:

@Repository
public interface MoviesRepository extends
    MongoRepository<ProductPages, String> {

    ... some method declarations to access movies ...
}

Is there an annotation driven way to tell the repository which template to use? If not, what else could be done to solve the problem?

like image 674
wmax Avatar asked Nov 05 '13 14:11

wmax


1 Answers

You have to use this annotation on the Configuration class

@EnableMongoRepositories(
basePackages = {"com.yyy.dao.jpa", "com.xxx.dao.jpa"},
mongoTemplateRef = "MovieTemplate"
)

and configure this:

  1. enumerate all the packages/classes to scan to find mongo dao that will be included on this configuration
  2. specify the MongoTemplate(bean name) that will be used by the Mongo Dao scanned by this configuration

So you need a configuration class for every set of Mongo Dao along with their corresponding MongoTemplate.

NOTE: If you intend to use a different Mongo client for each template, then you have to make sure the appropriate Mongo client bean is passed to the MongoTemplate, such as using a Qualifier, or a different argument name that matches the Mongo's method name with declared @Bean.

like image 97
vine Avatar answered Oct 15 '22 21:10

vine