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
Why Do Constructors in Java Not Have a Return Type
What Is an Instance Variable in Java
Java_Home Should Point to a Jdk Not a Jre
Java Array with More Than 4Gb Elements
Why String.Replaceall() in Java Requires 4 Slashes "\\\\" in Regex to Actually Replace "\"
How to Set an Environment Variable at Runtime from Java
Difference Between Webdriver.Get() and Webdriver.Navigate()
Is There Something Like Instanceof(Class<> C) in Java
Getting Class Cast Exception Where Both Classes Are Exactly the Same
Java:Read Last N Lines of a Huge File
Using Variables Outside of an If-Statement
Error 415 Unsupported Media Type: Post Not Reaching Rest If JSON, But It Does If Xml
Create File with Given Size in Java
How to Read Excel Cell Having Date with Apache Poi
Getting Nosuchmethoderror:Javax.Servlet.Servletcontext.Getvirtualservername()