Making Spring-Data-Mongodb Multi-Tenant

Spring Data MongoDB: how to implement multi-tenancy in CrudRepository

I finally decided to implement multi-tenancy at service layer as suggested by Markus W Mahlberg in his comment.

At repository level I created a findByTenantIdAndId query to check if a certain entity/document id belongs to the proper tenant.

I have a custom implementation of UserDetails interface, storing tenantId for logged user. I retrieve logged user at service layer via SecurityContextHolder.

Collection based multitenancy with Spring Data MongoDB

Found a way to recreate the indexes for a given tenant:

String tenantName = ...;

MongoMappingContext mappingContext = (MongoMappingContext) mongoTemplate.getConverter().getMappingContext();
MongoPersistentEntityIndexResolver resolver = new MongoPersistentEntityIndexResolver(mappingContext);

for (BasicMongoPersistentEntity entity : mappingContext.getPersistentEntities()) {
if (entity.findAnnotation(Document.class) == null) {
// Keep only collection roots
continue;
}

String collectionName = entity.getCollection();
if (!collectionName.startsWith(tenantName)) {
// Keep only dynamic entities
continue;
}

IndexOperations indexOperations = mongoTemplate.indexOps(collectionName);
for (MongoPersistentEntityIndexResolver.IndexDefinitionHolder holder : resolver.resolveIndexForEntity(entity)) {
indexOperations.ensureIndex(holder.getIndexDefinition());
}
}

Took me some time to figure this out. Hope this will help. Improvements welcome.



Related Topics



Leave a reply



Submit