【问题标题】:App Engine Datastore and low-level APIApp Engine 数据存储区和低级 API
【发布时间】:2013-06-27 12:45:36
【问题描述】:

我正在尝试使用 App Engine 数据存储(High Replication Datastore,HRD)并且我必须使用低级 API。我以前从未使用过实体数据库,所以我遇到了一些问题。我已经尝试存储一些 Post 和 cmets,每个 post 可以有更多的 cmets

I tried this code for Post, but the problem is how to make ID auto-increment ?
Entity post = new Entity("post", ID);
post.setProperty("content", postContent);
post.setProperty("time", timeStamps);

这段代码用于评论,但我不明白如何使用祖先来建立帖子和评论之间的关系,我应该添加祖先属性并将ID值放在上面吗?

Entity comment = new Entity("comment", ID);
comment.setProperty("ancestor",postID);
comment.setProperty("content", commentContent);
comment.setProperty("time", timeStamps);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(comment);

【问题讨论】:

    标签: java google-app-engine google-cloud-datastore low-level-api


    【解决方案1】:

    要使用自动增量功能,您需要更改应用的配置以使用旧版密钥生成:

    <auto-id-policy>
     legacy
    </auto-id-policy>
    

    然后您可以将代码更改为以下内容:

    Entity post = new Entity("post");
    post.setProperty("content", postContent);
    post.setProperty("time", timeStamps);
    

    如果你不传递 ID,appengine 会生成它

    要使用祖先路径,您可以将代码更改为以下内容:

    datastore.put(post);    
    Entity comment = new Entity("comment", post.getKey());
    comment.setProperty("content", commentContent);
    comment.setProperty("time", timeStamps);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.put(comment);
    

    祖先键将作为构造函数参数。

    我建议您使用默认密钥生成而不是自动增量,这不是增量但仍然是唯一的,
    它也应该更快,然后是旧版

    【讨论】: