Java – Making spring-data-mongodb multi-tenant


In a post last august sbzoom proposed a solution to make spring-data-mongoDB multi-tenant:

"You have to make your own RepositoryFactoryBean. Here is the example from the Spring Data MongoDB Reference Docs. You would still have to implement your own MongoTemplate and delay or remove the ensureIndexes() call. But you would have to rewrite a few classes to make sure your MongoTemplate is called instead of Spring's."

Did anybody implement this or something equivalent?

Best Solution

There's quite a few ways to skin the cat here. It essentially all boils down to on which level you'd like to apply the tenancy.


The basic approach is to bind some kind of key identifying the customer on a per-thread basis, so that you can find out about the customer the current thread of execution deals with. This is usually achieved by populating a ThreadLocal with some authentication related information as you can usually derive the tenant from the logged in user.

Now if that's in place there's a few options of where to apply the tenant knowledge. Let me briefly outline the most common ones:

Multi-tenancy on the database level

One way to separate data for multiple clients is to have individual databases per tenant. Spring Data MongoDB's core abstraction for this is the MongoDBFactory interface. The easiest way here is to override SimpleMongoDbFactory.getDb(String name) and call the parent method with the database name e.g. enriched by the tenant prefix or the like.

Multi-tenancy on the collection level

Another option is to have tenant specific collections, e.g. through tenant pre- or postfixes. This mechanism can actually be leveraged by using the Spring Expression language (SpEl) in the @Document annotation's collectionName attribute. First, expose the tenant prefix through a Spring bean:

 public class TenantProvider {

   public String getTenantId() {
     // … implement ThreadLocal lookup here

Then use SpEL in your domain types @Document mapping:

 @Document(collectionName = "#{tenantProvider.getTenantId()}_accounts"
 public class Account { … }

SpEl allows you to refer to Spring beans by name and execute methods on them. MongoTemplate (and thus the repository abstraction transitively) will use the mapping metadata of the document class and the mapping subsystem will evaluate the collectionName attribute to find out about the collection to interact with.