What you are trying to do is fundamentally wrong. Your desire is to have your query return results ordered by key; the very same thing that uniquely identifies your entity within the datastore. I cannot understand why you would want to do this since the key is derived using the Kind, Id and optionally the parent, if your class has one, as such I can't see how this ordering by key could ever be useful, but I am sure you have your reasons for wanting this. Perhaps you could expand on your question by explaining fully what you're trying to achieve.
Now I will attempt to answer your questions on why your queries aren't returning your desired results and suggest some solutions:
Your first query:
MainObjectlastUrl = OfyService.ofy().load().type(MainObject.class).ancestor(parent).order("-key").first().now();
The reason this query is returning null
is because the key
property you are passing as the condition to the order
method to sort against is not a field of your MainObject
entity. It does not exist and will always return null
when objectify tries to apply the sort order.
The same applies to your second query. It returns an empty list because there are not entities of type MainObject
with a key field. The only difference to the first query is that you are specifically requesting a list of entities rather than calling first()
.
The third query
list = OfyService.ofy().load().type(MainObject.class).ancestor(parent).list();
This query works, of course, because you are querying for all entities of type MainObject
that are ancestors of specified `parent' entity. Since such entities exist the query returns the expected results.
As you can see, the assumption that an entity's "key" somehow intrinsically exists as a property of your entity is incorrect. In order to use it sort by Key
you would need to add, say a property key
to your entity 'MainObject' to hold the value of entity's generated key, which would not make sense and definitely not recommended.
Caveat: there may be a way of getting hold of the key since we know it exists but I am not aware. Perhaps some datastore expert can shed light on this.
I suggest you sort using the indexed properties on your class which make sense within the domain of your application. For example sort by id
, since it isn't auto-generated and is likely to have some meaning; ditto for the date
property as they're both likely to have some domain value, as opposed to the key
. Hope this helps!