1

Iam running a Spring Boot application accessing MongoDB by implementing MongoRepository as described in the docs.

Following problem: I have the requirment to switch the collection name depending on the user who is accessing the data due to data security and control mechanisms. If user "A" wants to get "Product" collection he may access "products_a". For another user "B" wanting to get "Product" he may access "products_b".

a) I have seen solutions using SpEL but they seem not to be threadsafe meaning that users could interfere with each others data. The solution was to enhance the repository class with methods get, setCollectionName. https://stackoverflow.com/a/51095058/1548679

b) Manage multiple instances of the ProductRepository with different collectionNames. User requests a product, at that time the service knows which "data-realm" the user belongs to and has determined the correct collection name (e.g. "products_xyz"). A service to get the ProductRepository is now used which will look up the instance that is bound to "products_xyz" and returns it else it will be created and the instance added to the service for later access. Very simple implementation of https://en.wikipedia.org/wiki/Object_pool_pattern . I don't know if there is a better, more SpringBoot like solution but for me right now it seems to be the most tractable one.

c) Start an own application instance per "realm". One realm has a handful of users which have a common data access right. They access the same collections (e.g. products_a product_b but not both). So I could ramp up two SpringApplications. Problem: I would just pass the problem to the ServiceDiscovery and would unreasonably (at this moment at least) increase the servers' load.

Actually I don't have any code on this issue by now but I'll start with b) in the mean-time. Reading docs and online ressources didn't bring me to a spring common solution. This is not a direct "my code is not working question". It is more like "is that really the way to code it" question as Iam not really sure if there are any pitfalls or better ways.

Thanks in advance.

sascha10000
  • 1,245
  • 1
  • 10
  • 22
  • 1
    See if this gives you ideas also, https://callistaenterprise.se/blogg/teknik/2020/10/10/multi-tenancy-with-spring-boot-part4/ – JCompetence Dec 02 '21 at 13:46
  • 1
    Thanks. This is basically going in the same direction. But it is a lot boilerplate... Phew. I was also searching for the right word not thinking of multi-tenancy with that on my hand I found https://github.com/arun2pratap/multitenant-spring-mongodb . – sascha10000 Dec 02 '21 at 14:02

0 Answers0