如何在Google Cloud Datastore中添加数组属性值

时间:2014-05-25 17:46:46

标签: java google-cloud-datastore

如何在属性值中添加string或int数组? 这是我的代码,但它不起作用

   while(i<ValueArray.length)
                {               
                entityBuilder.addProperty(Property.newBuilder()
                      .setName(name))
                       .setValue(Value.newBuilder().setStringValue(ValueArray[i])));
                i++;}

提前谢谢你,

1 个答案:

答案 0 :(得分:1)

您可以使用列表值:

Value.Builder listValueBuilder = Value.newBuilder();
for (String value : values) {
  listValueBuilder.addListValue(Value.newBuilder().setStringValue(value));
}
entityBuilder.addProperty(Property.newBuilder()
    .setName(name)
    .setValue(listValueBuilder));

或者,使用DatastoreHelper中的便捷方法:

Value.Builder[] valueArray = new Value.Builder[values.length];
for (int i = 0; i < values.length; i++) {
  valueArray[i] = DatastoreHelper.makeValue(values[i]);
}
entityBuilder.addProperty(
    DatastoreHelper.makeProperty(name, DatastoreHelper.makeValue(valueArray)));

并检索值:

for (Property property : entity.getPropertyList()) {
  // Find the list property by name.
  if (property.getName().equals(name)) {
    for (Value value : property.getValue().getListValueList()) {
      // Print each string value from the list value.
      System.out.println(value.getStringValue());
    }
  }
}

或者,再次使用DatastoreHelper

Map<String, Value> propertyMap = DatastoreHelper.getPropertyMap(entity);
for (Value value : propertyMap.get(name).getListValueList()) {
  // Print each string value from the list value.
  System.out.println(value.getStringValue());
}