Automatic ID for embedded entity

2019-07-23 09:16发布

Is there a way to let the datastore assign an automatic ID for an embedded entity? I use Mutation.Builder.addInsertAutoId and it works on "normal" entities, but I get an error when trying to generate an ID for an embedded entity:

ApplicationError: 1: Entity is missing key.

Example code

Entity.Builder entity = Entity.newBuilder();
Key.Builder key = makeKey(m.getClass().getSimpleName());
entity.setKey(key);
entity.addProperty(makeProperty("name", makeValue(m.getName())));

Entity.Builder embeddedEntity = Entity.newBuilder();
addProperty(embeddedEntity, "name", "a different name");

entity.addProperty(makeProperty("embedded", makeValue(embeddedEntity).setIndexed(false)));

CommitRequest req = CommitRequest.newBuilder()
        .setMode(CommitRequest.Mode.NON_TRANSACTIONAL)
        .setMutation(
                Mutation.newBuilder()
                        .addInsertAutoId(entity)
                        .addInsertAutoId(embeddedEntity)
        )
        .build();

The stack trace

com.google.apphosting.api.ApiProxy$ApplicationException: ApplicationError: 1: Entity is missing key.
    at com.google.appengine.api.datastore.dev.LocalDatastoreV4Service.commit(LocalDatastoreV4Service.java:162)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.callInternal(ApiProxyLocalImpl.java:521)
    at com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.call(ApiProxyLocalImpl.java:475)
    at com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.call(ApiProxyLocalImpl.java:452)
    at java.util.concurrent.Executors$PrivilegedCallable$1.run(Executors.java:533)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.concurrent.Executors$PrivilegedCallable.call(Executors.java:530)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

I tried different variations and it does not matter at what point I call addInsertAutoId.

1条回答
ら.Afraid
2楼-- · 2019-07-23 09:22

Setting a 'stub' key, as shown in the examples for App Engine, does the trick:

Entity.Builder embeddedEntity = Entity.newBuilder();
addProperty(embeddedEntity, "name", "a different name");
embeddedEntity.setKey(entity.getKey)                      // ← required
查看更多
登录 后发表回答