Results 1 to 4 of 4

Thread: Multiple collections to store same entity

  1. #1
    Join Date
    Mar 2012
    Posts
    4

    Default 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. #2
    Join Date
    Apr 2006
    Location
    Dresden, Germany
    Posts
    483

    Default

    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.

  3. #3
    Join Date
    Mar 2012
    Posts
    4

    Default

    Wow! As simple as it can get.

    Will try and update the thread.

    Thanks,
    Sid
    Regards,
    Sid

  4. #4
    Join Date
    Sep 2010
    Posts
    5

    Default

    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

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •