Michael Litherland
Michael Litherland

Reputation: 38

Datastore get not finding record by key

I've been banging my head against this for an embarrassing amount of time, and appreciate any help. I have what I think is a simple scenario where I'm trying to retrieve and update an entity if it exists, or create a new if it doesn't. There's a parent entity, and that part seems to work fine. I create the child key like this:

Key someKey = KeyFactory.createKey(parent.getKey(), CHILD_KIND, child.getUniqueStringValue());

According to the documents I read doing a get on this would return the entity if it existed:

Entity someChild = datastore.get(someKey);

But it doesn't. Instead I have to do a:

Query query = new Query(CHILD_KIND, someKey);
Entity someChild = datastore.prepare(query).asSingleEntity();

to find it. If I try to log the someKey.toString() value, they look the same during creation as they do during a search, but it still only finds them if I do the query instead of the get. I'm missing something stupid and obvious and searching has gotten me nowhere over the course of about a week, so I appreciate any help.

Thanks, Mike

Edit:

To clarify how I'm creating the child entity, it's like this:

Key someKey = KeyFactory.createKey(parent.getKey(), CHILD_KIND, child.getUniqueStringValue());
Entity someChild = new Entity(CHILD_KIND, someKey);
someChild.setProperty("desc", child.getUniqueStringValue());
someChild.setProperty("createTime", child.getCreateTime());
// and then a few more values that are timestamps or null

Upvotes: 1

Views: 205

Answers (2)

Ying Li
Ying Li

Reputation: 2519

The problem is that you are confusing Parent_Key with Key.

This line:

Entity someChild = new Entity(CHILD_KIND, someKey);

Creates an Entity of the kind "CHILD_KIND" with parent entity of key "someKey". See this document for details [1].

When you do a simple datastore.get(key), you are using the Entity's own key, not the parent key. So what you need to do is use KeyFactory to get the Entity Key from its Parent Key, Kind, Name. The details can be found here [2] and here [3].

[1] - https://cloud.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/Entity [2] - https://cloud.google.com/appengine/docs/java/datastore/entities#Java_Retrieving_an_entity [3] - https://cloud.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/KeyFactory

Upvotes: 1

Andrei Volgin
Andrei Volgin

Reputation: 41099

There is a problem in the way you create a child entity. It should be:

Entity someChild = new Entity(CHILD_KIND, parent.getKey());

or

Entity someChild = new Entity(CHILD_KIND, child.getUniqueStringValue(), parent.getKey());

Also, I am not sure why you use child.getUniqueStringValue() instead of a simple Long id, which takes less space.

Upvotes: 2

Related Questions