I am using the latest spring-data-mongodb (1.1.0.M2) and the latest Mongo Driver (2.9.0-RC1). I have a situation where I have multiple clients connecting to my application a
The spot to look at is the MongoDbFactory
interface. The basic implementation of that takes a Mongo instance and works with that throughout all the application lifetime. To achieve a per-thread (and thus per-request) database usage you'll probably have to implement something along the lines of AbstractRoutingDataSource. The idea is pretty much that you have a template method that will have to lookup the tenant per invocation (ThreadLocal
bound I guess) and then select a Mongo
instance from a set of predefined ones or some custom logic to come up with a fresh one for a new tenant etc.
Keep in mind that MongoDbFactory
usually get's used through the getDb()
method. However, there are features in MongoDB that need us to provide a getDb(String name)
. DBRef
s (sth. like a foreign key in the relational world) can point to documents an entirely different database. So if you're doing the delegation either avoid using that feature (I think the DBRef
s pointing to another DB are the only places calling getDb(name)
) or explicitly handle it.
From a configuration point of view you could either simply override mongoDbFactory()
entirely or simply not extend the base class at all and come up with your own Java based configuration.