I've been trying to get an entity from GAE datastore by its key, which is of type Key. Here's the code that开发者_Python百科 I'm using to retrieve the key:
strId = myVideo.getKey().toString();
The type of myVideo is Entity. The value that the myVideo.getKey().toString()
method returns is "Video(121)". Here's the code that tries to retrieve the entity via the entity's key:
Entity video = ds.get(key);
The following exception gets thrown when trying to retrieve the entity from the datastore:
No entity was found matching the key: Video("Video(121)")
Is there a way to get the encoded key from an object of type Entity?
The various ways to convert between keys and strings are documented in the App Engine docs here. In short, to get a string version of the key, you want to do this:
String employeeKeyStr = KeyFactory.keyToString(employeeKey);
To convert it back to a key you can fetch with ds.get()
, you should do this:
Key employeeKey = KeyFactory.stringToKey(employeeKeyStr);
The string version you're fetching with .toString()
is a human readable version of the key, not intended to be passed around as a machine-readable identifier.
Of course, if you are intending to pass keys around your code, there's no need to convert them to strings at all. Conversely, if you want to use them as external identifiers, you probably want to read the rest of the linked section, which discusses ancestors, IDs and names; most of the time when you want to pass identifiers around, the name or ID alone will suffice, and is shorter and more readable than the full key.
I found that passing in a string type in the KeyFactory.createKey(Video.class.getSimpleName(), Integer.parseInt(videoID));
was the cause of the problem. The key needs to consist of an integer if you're using a key of type Key, hence the datatype cast: Integer.parseInt(videoID)
.
精彩评论