Tom Tom - 2 months ago 12
Java Question

Why Google does datastore allow duplicated ID/Name? And what is the best practice for managing this?

Ok, now see this code

public void insertUser1(){
public static Key personKey=KeyFactory.createKey("Person", "PersonName");
Entity userEntity=new Entity("User", "User1", personKey);
userEntity.setProperty("FirstName","Tom");
datastore.put(userEntity);
}


After ran
insertUser1();
, you can see it in datastore


ID/Name - FirstName
User1 - Tom


Now, I want to modify firstname of user1 but this time I use this code

public void modifyUser1(){
Entity userEntity=new Entity("User", "User1");
userEntity.setProperty("FirstName","Mary");
datastore.put(userEntity);
}


Now, check datastore again, I can see 2 entries:


ID/Name - FirstName
User1 - Tom
User1 - Mary


Why Google does datastore allow duplicated ID/Name? And what is the best practice for managing this?

Answer

First one have parent, second one doesn't.

public static Key personKey=KeyFactory.createKey("Person", "PersonName");
Entity userEntity=new Entity("User", "User1", personKey);

have id Key(Key(Person,PersonName), User, User1)

but this:

new Entity("User", "User1");

just Key(User, User1). So it's different ids.

Basically it's entity Key that unique per database, and it consists of Parent Id (or empty) and Entity Id.

Read more about entity parents: https://cloud.google.com/appengine/docs/java/datastore/#Java_Ancestor_paths