Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objectify, how do you load an entity by ID without knowing the parent key?

I have an entity group in objectify, typical SomeParentClass and SomeChildClass. I want to do something like this to load an instance of SomeChildClass from the datastore.

ofy().load.type(SomeChildClass.class).id(idOfSomeChildClassInstace);

This is returning nothing found. Seems that you need to know the parent of SomeChildClass to get it from the datestore. This I know works.

Key<SomeChildClass> k = Key.create(someParentClass.generateKey(), SomeChildClass.class, idOfSomeChildClassInstace);
ofy().load().key(k).now;

What if I want to load an instance of SomeChildClass without knowing the parent, by just having the id of SomeChildClass.

like image 785
Marc M. Avatar asked Dec 01 '22 18:12

Marc M.


2 Answers

You cannot do that - the actual full identifier of an entity is the kind and id of each of its ancestors as well as it's own kind and id. That is why building the full key works, but using just the child entity id does not. Another way of looking at it that ids are only unique between siblings of the same parent.

The easiest way to solve your issue is to produce a key for your child entity, then get the 'web safe string' for it. This string contains all the information of the entity and all it's parents and can be used to fully reconstitute the full id.

Using objectify:

String websafeKey = Key.create(parentKey, Entity.class, id).getString();
Key<Entity> key = Key.create(websafeKey);

You can also do this with the low level api if you need to.

like image 124
Nick Avatar answered Dec 16 '22 02:12

Nick


You need to know the whole Key to be able to get() an entity. A child key consists of: kind, ID and parent key. So you need to provide all three.

like image 28
Peter Knego Avatar answered Dec 16 '22 03:12

Peter Knego