Selecting based on __key__ (a unique identifier) in google appengine [Java]
-
04-10-2019 - |
Question
I have
public class QuantityType {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String type;
}
I am trying to setup a query to get the right QuantityType by it's key
gql = "select * from QuantityType where __key__='aght52oobW1hIHTWVzc2FnZRiyAQw'";
But its not working because
BadFilterError: BadFilterError: invalid filter: key filter value must be a Key; received aght52oobW1hIHTWVzc2FnZRiyAQw (a str).
I have also tried to use
gql = "select * from QuantityType where __key__=='" + KeyFactory.stringToKey(qTypeKey)+"'";
but it's not working..
How can I get a specific object from my datastore by it's key?
Solution
First, you should never construct a GQL string by hand - this leads to injection vulnerabilities. Instead, declare and pass in parameters, as documented here.
To retrieve an entity by key, though, you don't need to do a query at all: Use getObjectById, as documented here. This is significantly faster than using a query.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow