Getting a GAE Object by Key

I am trying to get an entity from a GAE data store with my key, which is of type Key. Here is the code I use to extract the key:

strId = myVideo.getKey().toString(); 

The type myVideo is Entity. The value returned by the myVideo.getKey().toString() method is "Video (121)". Here is the code that is trying to get the object through the entity key:

 Entity video = ds.get(key); 

When trying to retrieve an object from the data store, the following exception occurs:

No objects were found matching the key: Video ("Video (121)")

Is there a way to get the encoded key for an entity of type Entity?

+4
source share
2 answers

I found that the cause of the problem is passing the string type to KeyFactory.createKey(Video.class.getSimpleName(), Integer.parseInt(videoID)); . The key must be an integer if you use a key of type Key, therefore, the data type is Integer.parseInt(videoID) .

+2
source

Different ways to convert between keys and strings are described in App Engine docs here . In short, to get a lowercase version of a key, you want to do this:

 String employeeKeyStr = KeyFactory.keyToString(employeeKey); 

To convert it back to a key, which you can get with ds.get() , you have to do this:

 Key employeeKey = KeyFactory.stringToKey(employeeKeyStr); 

The string version that you retrieve with .toString() is a human-readable version of the key, not intended to be transmitted as a machine-readable identifier.

Of course, if you are going to transfer keys around your code, there is no need to convert them into strings. Conversely, if you want to use them as external identifiers, you probably want to read the rest of the related section, which discusses ancestors, identifiers, and names; most of the time when you want to pass identifiers, the name or identifier will be sufficient and shorter and more readable than the full key.

+4
source

Source: https://habr.com/ru/post/1341033/


All Articles