In JDO (AppEngine), after persisting an object, how can i get the key of that particular object?
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 K开发者_如何学Pythoney 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.
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."
精彩评论