通过键获取 GAE 实体
我一直在尝试通过其密钥(类型为 Key)从 GAE 数据存储中获取实体。这是我用来检索密钥的代码:
strId = myVideo.getKey().toString();
myVideo 的类型是 Entity。 myVideo.getKey().toString()
方法返回的值为“Video(121)”。以下是尝试通过实体的键检索实体的代码:
Entity video = ds.get(key);
尝试从数据存储区检索实体时会引发以下异常:
未找到与键匹配的实体: 视频(“视频(121)”)
有没有办法从 Entity 类型的对象获取编码密钥?
I've been trying to get an entity from GAE datastore by its key, which is of type Key. Here's the code that 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
App Engine 文档中记录了在键和字符串之间进行转换的各种方法 这里。简而言之,要获取密钥的字符串版本,您需要执行以下操作:
要将其转换回可以使用 ds.get() 获取的密钥,您应该执行以下操作:
字符串版本您使用
.toString()
获取的是密钥的人类可读版本,而不是作为机器可读标识符传递。当然,如果您打算在代码中传递密钥,则根本不需要将它们转换为字符串。相反,如果您想将它们用作外部标识符,您可能需要阅读链接部分的其余部分,其中讨论了祖先、ID 和名称;大多数时候,当您想要传递标识符时,仅名称或 ID 就足够了,并且比完整密钥更短且更具可读性。
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:
To convert it back to a key you can fetch with
ds.get()
, you should do this: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.
我发现在
KeyFactory.createKey(Video.class.getSimpleName(), Integer.parseInt(videoID));
中传入字符串类型是问题的原因。如果您使用 Key 类型的键,则该键需要由整数组成,因此数据类型转换为:Integer.parseInt(videoID)
。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)
.