I have a spring boot tenant application that needs to access multiple tenant databases. All of the databases are on a single MongoDB server. Each tenant has there own database that is password protected. I have been able to get it to work using MongoClient as shown below.
MongoClient mongoClient = new MongoClient(mongoConnectionUri,
mongoCredentials);
DB tenantDB = mongoClient.getDB(tenantWebRequest.getNewTenantId());
MongoClient is simple to use and as shown above and can easily connect to runtime mongo databases. However, MongoClient is programmatically clumsy when writing/query documents to the database. I would rather use MongoRespository with its very powerful CRUD and custom query methods. Here is the code for a single MongoDB Repository
public class MongoConfig extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return mongodbname;
}
@Override
public Mongo mongo() throws Exception {
return new MongoClient(mongoconnectionuri, mongoport);
}
// Mongo Connection URI
@Value("${spring.data.mongodb.uri}")
private String mongoconnectionuri;
// Mongo Connection Port
@Value("${spring.data.mongodb.port}")
private int mongoport;
// Mongo Tenant Authorization database
@Value("${spring.data.mongodb.database}")
private String mongodbname;
}
The repository looks like,
public interface UserRepository extends MongoRepository< Tenant, String>{
public User findByTenantname(String tenantname);
}
This repository works great for a single static database. How do I get repositories to work where I can create and access at runtime different tenant databases? I don't know the names of the tenants ahead of time. When a new tenant signs up for the service they access a web service and type in their new tenant name. I use the name and create a new tenant database with several collections initialized with customer metadata. I am using spring boot with annotations along with Gradle.