Announcement Announcement Module
Collapse
No announcement yet.
Multiple collections to store same entity Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Multiple collections to store same entity

    Hi,

    We have decided to separate our collections using namespaces. i.e. Separate collection per customer. The document structure is the same for all collections and hence we have one entity annotated as @Document in mid-tier. We use SimpleMongoRepository provided by Spring Data and hence there is no control to manipulate the collection name as it is picked up from MongoEntityInformation.getCollectionName().

    I am struggling to find the code by which I can deduce which collection to pick given the same entity?

    Ex.

    @Document
    class Foo {

    @Id
    String id;
    String name;
    String customer;

    }

    If customer = "A" - collection should be a.foo
    If customer = "B" - collection should be b.foo etc

    I have tried
    Any pointers will be appreciated?

    Thx,
    Sid

  • #2
    The collection name is basically determined in BasicMongoPersistentEntity.getCollectionName(). This method is called whenever we have to decide which collection to interact with. The implementation uses a SpEL expression parser to evaluate the configured String as it might contain an EL expression. So here's how you can achieve what you want:

    1. Create a Spring Bean do implement the logic to determine the customer specific part

    Code:
    @Component("customer")
    class CollectionNameStrategy {
    
      String part() {
        // implement here
      }
    }
    3. Configure a SpEL expression inside the @Document annotation

    Code:
    @Document("#{@customer.part() + '.accounts'}"
    class Accounts {
    
    }
    @customer refers to the Spring bean named "customer" above and will call the part() method for each evaluation.

    Comment


    • #3
      Wow! As simple as it can get.

      Will try and update the thread.

      Thanks,
      Sid

      Comment


      • #4
        Maybe my query is more related to SPEL,
        but how can I access my Accounts instance inside part() method?

        @Component("customer")
        class CollectionNameStrategy {

        String part(Accounts accounts) {
        accounts.getDetails(); //for eg
        }
        }

        Basically, my use case is the same as mentioned by ssharma above.
        In addition, I want to access instance of entity being annotated with Document inside the part() method.

        Thanks,
        Ratish

        Comment

        Working...
        X