开发者

In JDO (AppEngine), after persisting an object, how can i get the key of that particular object?

开发者 https://www.devze.com 2023-02-13 14:04 出处:网络
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:

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."

0

精彩评论

暂无评论...
验证码 换一张
取 消