124697
124697

Reputation: 21893

KeyFactory.createKey() Is this the correct way of storing data in Datastore

each user can have many questions. questions can only have one user. is the following correct

Key questionKey = KeyFactory.createKey("Questions", userId);
Entity questionEntity = new Entity("Question", questionKey);
questionEntity.setProperty("questionCategory", questionCategory);
...

Upvotes: 1

Views: 1940

Answers (1)

tony m
tony m

Reputation: 4779

The given usage is wrong. For the question, you are creating key using kind and userid . This implies the corresponding entity is of Kind="Questions" and id=userid and no parents. This is wrong and you will start getting errors once you have more than 1 question for a user as they will all have the same key.

Ideally what you need is that for a question entity, declare its kind as question and parent as the user as follows :

1, If using manually generated id or name for a question , then :

Key questionKey = KeyFactory.createKey(userkey, "Questions", questionidorname);

2, If using app engine's auto generate id, then no need create key, instead create entity as:

Entity questionEntity = new Entity("Questions",
      userkey)

Here userkey is the key of a user entity

Upvotes: 2

Related Questions