如何通过 Google Cloud Datastore JSON API 存储 class 和子 class?

How to store class with sub class by Google Cloud Datastore JSON API?

为了存储到 GCD,我想使用 Google Cloud Datastore JSON API 但我无法用另一个 [=41] 为对象编写正确的 Json 请求主体=] 会员。考虑一下我有 2 classes :

public class Foo {
    private String id;
    private Bar bar;
    // getter and setter...
}

public class Bar {
    private String name;
    private String pass;
    // getter and setter...
}

然后我创建一个 Foo class 的对象,其中包含一个 Bar class 的对象。 所以我想将这个对象插入到 Cloud Datastore。我写了这个请求正文:

{
  "transaction":"some bytes",
  "mutation":{
    "insert":[
      {
        "key":{
          "partitionId":{
            "datasetId":"s~my-dataset-id"
          },
          "path":[
            {
              "kind":"Foo",
              "name":"id"
            }
          ]
        },
        "properties":{
          "bar":{
            "entityValue":{
              "name":{
                "stringValue":"Jack"
              },
              "pass":{
                "stringValue":"1234"
              }
            },
            "indexed":false
          },
          "id":{
            "stringValue":"id"
          }
        }
      }
    ]
  }
}

然后除 bar 之外的所有字段都将保存到云数据存储中。我使用了 "entityValue" 但似乎我应该包括整个实体结构(感谢 Adam 提到它)。但我不需要它作为另一个实体,显然我不应该使用 "entityValue"。 那么我应该如何更改请求主体以插入这样的对象?

顺便说一下,我可以通过以下请求插入一个 Bar 对象(但不是 Foo):

   {
  "transaction":"some bytes",
  "mutation":{
    "insert":[
      {
        "key":{
          "partitionId":{
            "datasetId":"s~my-project-id"
          },
          "path":[
            {
              "kind":"Bar",
              "name":"John"
            }
          ]
        },
        "properties":{
          "pass":{
            "stringValue":"1234"
          },
          "name":{
            "stringValue":"John"
          }
        }
      }
    ]
  }
}

这是相关的 link : Related link

您必须包含 'entityValue' 的整个实体结构(包括 "key" 和 "properties" 字段)。这是因为您引用的是数据存储区中的一个单独实体,而不仅仅是当前实体中嵌入的另一个数据结构。参见:

数据集:实体格式
https://cloud.google.com/datastore/docs/apis/v1beta2/entity

字段 'entityValue": (Entity)' 是一个线索,您需要从同一实体表示的开头开始新实体。

您可以将 Bar 添加为 entityValue。这个值看起来像一个普通的实体,但它不需要有键。此实体值 不需要 单独存在于数据存储中。

例如:

{
  "mutation":{
    "insert":[
      {
        "key":{
          "path":[
            {
              "kind":"Foo",
              "name":"id"
            }
          ]
        },
        "properties":{
          "bar":{
            "entityValue":{
              "properties": {
                "name":{
                  "stringValue":"Jack"
                },
                "pass":{
                  "stringValue":"1234"
                }
              }
            },
            "indexed":false
          },
          "id":{
            "stringValue":"id"
          }
        }
      }
    ]
  },
  "mode": "NON_TRANSACTIONAL"
}

另请注意,此处 Foo 的键省略了 partitionId。这是首选,Datastore 会为您填写正确的 partitionId