【问题标题】:Google Datastore - Ensure only one entity is created for an entity with a specific ancestor keyGoogle Datastore - 确保只为具有特定祖先键的实体创建一个实体
【发布时间】:2020-05-04 22:13:13
【问题描述】:

我想确保只为具有特定祖先键的实体创建一个实体。我的解决方案是将祖先查询放在事务中,检查实体是否存在,如果不存在,则创建它。

这会确保只存在一个具有特定祖先键的实体吗?

ofy().transact(new VoidWork() {
    public void vrun() {

            Entity entity = ofy().load().type(Entity.class)
                    .ancestor(ancestorKey)
                    .first()
                    .now();

            if (entity == null) {
                // Entity does not exist. Create it.
                final Entity newEntity = new Entity(ancestorKey);

                ofy().save().entity(newEntity).now();
            } else {
                // Entity already exists.
            }

        }
    }
});

【问题讨论】:

    标签: google-app-engine google-cloud-datastore objectify


    【解决方案1】:

    SO 不喜欢一个字的答案,所以我不能只说“是”。

    如果您只是想确保只有一件事存在,则不需要祖先查询 - 只需对已知 id 执行按键获取即可。

    既然 Java7 已经消失,没有理由不把它放在 lambda 中。

    【讨论】:

    • 我需要那里的祖先进行其他查询。对于一个实体(假设我知道父实体 id):Entity entity = ofy().load().type(Entity.class).parent(ParentEntity.class).id(parentEntityId).now();
    • 不,parent() 传入实体对象或键对象(参见Key.create())。而你传入的id() 是给孩子的。
    • 我明白了,像这样吗? Entity entity = ofy().load().type(Entity.class).parent(parentEntity).id(entityId).now(); 以及 Entity entity = ofy().load().type(Entity.class).parent(Key.create(ParentEntity.class, parentEntityId)).id(entityId).now();
    • 另外,使用父实体 ID 作为子实体 ID 是否也安全?这样可以很容易地查看某个父级在执行 get-by-key 时是否存在子级。
    • 你引用的代码看起来没问题。你的第二个问题让我很困惑。请记住,实体的唯一标识符是 {parent, id}。特定 id 仅对于给定的父级是唯一的(可能为 null)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2016-01-13
    • 2013-11-16
    相关资源
    最近更新 更多