什么时候在 gae 数据存储中存储 id 和密钥?

When do you store ids and when do you store keys in gae datastore?

假设我的数据存储模型如下所示:

@Entity
public class User {

    @Id
    private Long id;
    @Index
    private String email;
    private Long dateOfBirth;
    // More fields...
}

@Entity
public class Topic {

    @Id
    private Long id; 
    private String topicTitle;
    private Long date; 

}

@Entity
public class Comment {

    @Id
    private Long id;
    @Parent
    private Key<Topic> topicKey;
    private Long commenterId;
    private String text;
    private Long date;

}

其中实体 Comment 具有父实体 Topic。我知道在指定 @Parent 时应该存储密钥,就像我在 Comment 实体中所做的那样,但是否也应该存储 commenterId 的密钥?还是存储该用户的 Long id 就足够了?

只是想知道当其他实体不是父实体时,存储对其他实体的引用的最佳做法是什么 - 您应该存储 ID 并稍后生成密钥,还是只存储实体的密钥。有没有充分的理由让您先做一个再做另一个?

编辑:因为我使用的是 Cloud Endpoints,所以我从我的 AppEngine 项目中得到的响应是 JSON。客户端库中不允许使用参数化类型的密钥。所以对我来说,id 可以,Key<?> 也可以。请注意,您应该 return 为您的客户端提供网络安全版本:

myKey.getString();

通常没有理由将密钥存储为参考。密钥需要更多 space - 无论是在数据存储中,还是在您传输到客户端和从客户端传输的对象中。

仅当同一实体类型可以是其自身或另一个实体的子实体时,才可能需要使用键。这在技术上是可行的,一些数据模型可以使用这种方法,尽管它可能是一个非常罕见的用例。

注意:出于同样的原因(less space),我只在对象中使用父代的 ID。在数据存储实体中,父 ID 始终可以从子实体键中提取。我使用 low-level 数据存储区 API,但是 - 您需要检查如何在您使用的库中正确注释 child-parent 关系。