2

当我将一个对象持久化到数据存储区时,何时(以及如何)可以获得我刚刚持久化的特定对象的密钥?例如,如果我有:

@PersistenceCapable
public class Employee {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key id;
...
}

查询类:

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?关于如何有效地做到这一点的任何建议?

谢谢。

4

1 回答 1

3

一旦对象被持久化, 您就可以在Point 2中获取密钥。第 1 点太早了,第 3 点在发生异常时也会调用,所以不能保证有生成的密钥。

正如官方文档所说:“保存实例时会填充实例的长键字段。”

于 2011-02-27T18:31:26.770 回答