1

I have a case, where I need to switch between the mongo databases using Spring mongodata (Version: 1.6.2). Currently, I have default database configured in db-config.xml with mongo template, and have annotated repositories; Need is to switch from one db/template to another at runtime; do necessary actions and switch back to default one. I referred to couple of links, Spring-data-mongodb connect to multiple databases in one Mongo instance and Making spring-data-mongodb multi-tenant I need to use same set of repositories at runtime. Is it possible to handle my case at configuration level? or do we need to extend Dbfactory to achieve this? with Dbfactory, can I use same set of annotated repositories?

Appreciate any help.

2 Answers 2

2

You can extend:

   1.  `SimpleMongoDbFactory`: returning custom DB in DB `getDb(String dbName)`.

    2. `MongoTemplate`: Supplying above factory.

Use appropriate MongoTemplate with the help of @Qualifier.

Sign up to request clarification or add additional context in comments.

2 Comments

Amdalal, Can you please give us more information how to use the different mongo template for the same repository.
1

I once had a very similar problem. I published the code on github, check it out multi-tenant-spring-mongodb

You basically have to extend SimpleMongoDbFactory and handle other hosts too. I just did handle multiple databases on the same server. That shouldn't be a problem.

3 Comments

Thanks for the reply. As per your code, I understand, we can set mongo template only once. I tried connecting to different dbs on same server, this is working fine. But, In my case, databases are in different server boxes. Is it possible to connect to a db on different server, dynamically?
is this resolved? I was unable to update the database during runtime. context.getBean(SimpleMongoDbFactory.class).getDb("Test"); But it was not working, Thanks in advance.
@devanathan could you open a github issue instead? stackoverlflow isn't a bug tracker ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.