Home Multiple Spring Data MongoDB Connections
Post
Cancel

Multiple Spring Data MongoDB Connections

Using Spring Data Starter MongoDB to connect to multiple MongoDB databases is quite easy. Its less complicated when you use just MongoTemplate for all your queries. But gets complicated when you use both MongoTemplate and MongoRepository. MongoTemplate connects to the intended secondary datasource but MongoRepository still uses the primary(strange but true).

Fortunately there is a simple way to solve it.

1. Create your custom MongoTemplate bean for your secondary datasource.

1
2
3
4
5
6
7
8
9
10
@Bean
public Mongo mongo() throws Exception{
 return new MongoClient(host,port);
}

@Bean(autowire = Autowire.BY_NAME, name = "secondaryMongoTemplate")
public MongoTemplate secondaryMongoTemplate() throws Exception {
	return new MongoTemplate(mongo(),database);
}

2. And Finally @EnableMongoRepositories with the custom MongoTemplate

1
2
3
4
@EnableMongoRepositories(
    basePackages ={"this.is.your.repository.package"},
    mongoTemplateRef = "secondaryMongoTemplate"
  )

Now all MongoRepository implementations would use the same datasource configuration as your custom MongoTemplate.

Ok. Later.

This post is licensed under CC BY 4.0 by the author.