在JDO(AppEngine)中,持久化一个对象后,我如何获取该特定对象的密钥?

发布于 2024-10-19 05:40:42 字数 1076 浏览 1 评论 0原文

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

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌无敌 2024-10-26 05:40:42

一旦对象被持久化,您就可以在第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."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文