在JDO(AppEngine)中,持久化一个对象后,我如何获取该特定对象的密钥?
当我将一个对象持久保存到数据存储时,何时(以及如何)可以获得我刚刚持久保存的特定对象的密钥?例如,如果我有:
@PersistenceCapable
public class Employee {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key id;
...
}
Query 类:
public class EmployeeQuery {
// Persist a single Employee
public void persistEmployee(Employee e) {
// 1. Can I get the id at this point?
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(e);
// 2. Can I get the id at this point?
}
finally {
pm.close();
// 3. Can I get the id at this point?
}
}
...
}
可以在此处找到 PersistenceManager 和 PMF 信息:http://code.google.com/appengine/docs/java/datastore/jdo/overview.html#Getting_a_PersistenceManager_Instance
如上所述,在上述区域 (1、 2 或 3) 我可以获得该特定对象的自动生成的 id 吗?另外,如何获取该特定对象的 id?关于如何有效地做到这一点有什么建议吗?
谢谢。
When I persist an object to the datastore, when (and how) can I get the key of that particular object that I just persisted? So for example, if I have:
@PersistenceCapable
public class Employee {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key id;
...
}
The Query class:
public class EmployeeQuery {
// Persist a single Employee
public void persistEmployee(Employee e) {
// 1. Can I get the id at this point?
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(e);
// 2. Can I get the id at this point?
}
finally {
pm.close();
// 3. Can I get the id at this point?
}
}
...
}
The PersistenceManager and PMF information can be found here: http://code.google.com/appengine/docs/java/datastore/jdo/overview.html#Getting_a_PersistenceManager_Instance
As mentioned above, where in the mentioned areas (1, 2 or 3) can I get the auto-generated id of that particular object? Also, how can I get the id of that specific object? Any suggestions of how to do this efficiently?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一旦对象被持久化,您就可以在第2点中获取密钥。 第1点太早,发生异常时也会调用第3点,因此不能保证有生成的密钥。
正如官方文档 say : “保存实例时会填充实例的长键字段。”
You can get the key in Point 2, once the object is persisted. Point 1 is too early and Point 3 is also called when an exception occurs, so you can not guarantee to have a generated key.
As the official docs say : "The long key field of an instance is populated when the instance is saved."