javagoogle-app-enginegoogle-cloud-datastoreentity-relationshiplow-level-api

App engine datastore and Java low-level api: many to many relationship


I just wanna know how made a many to many relationship between two entity´s using the low level api in the datastore, I've been looking but I could not find documentation that explains how to do this kind of relationship. i hope some one can help.

but if I have the entity A and entity B in a many to many relationship how can i stored in the datastore. i mean, This a good solution to store a many to many realtionship in the datastore or what is a good solution? this code is ok or is wrong?

Entity entityA = new Entity("TypeA");
entityA.setProperty("name", "nameUserA");

Entity entityB = new Entity("TypeA");
entityA.setProperty("name", "nameUserB");

ds.put(entityA);
ds.put(entityB);

Entity entityChild = new Entity("entityChild",entityAKey);
entityChild.setProperty("name","child");

 ds.put(entityChild);

Entity entityChild = new Entity("entityChild",entityBKey);
entityChild.setProperty("name","child");

 ds.put(entityChild);

Solution

  • AppEngine doesn't provide any functionality for many-to-many relationship.

    You can emulate it, by creating your own entity, with two fields:

    class AtoBRelations {
      Key entityA 
      Key entityB
    }
    

    I's common pattern to have an extra table for many-to-many relationship, even for other databases

    BTW, for most cases it will be not optimal solution. Optimal solution depends on how this many-to-many relation have to be used, and there is few different solutions

    for example there is second solution: you can store a list of related entities, like:

    class EntityA {
       List<Key> entitiesB
    }