执行 CRUD 操作 - Amazon SDK for Java 2.x
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

执行 CRUD 操作

定义 EnhancedDocument 实例后,您可以将其保存到 DynamoDB 表。以下代码段使用基于单个元素创建的 personDocument

documentDynamoDbTable.putItem(personDocument);

读取 DynamoDB 中的增强型文档实例后,您可以使用 getter 提取各个属性值,如以下代码段所示,这些代码段用于访问从 personDocument 中保存的数据。或者,您可以将完整内容提取为 JSON 字符串,如示例代码的最后一部分所示。

// Read the item. EnhancedDocument personDocFromDb = documentDynamoDbTable.getItem(Key.builder().partitionValue(50).build()); // Access top-level attributes. logger.info("Name: {} {}", personDocFromDb.getString("firstName"), personDocFromDb.getString("lastName")); // Name: Shirley Rodriguez // Typesafe access of a deeply nested attribute. The addressMapEnhancedType shown previously defines the shape of an addresses map. Map<String, Map<String, String>> addresses = personDocFromDb.getMap("addresses", EnhancedType.of(String.class), addressMapEnhancedType); addresses.keySet().forEach(k -> logger.info(addresses.get(k).toString())); // {zipCode=00002, city=Any Town, street=123 Any Street, state=ME} // Alternatively, work with AttributeValue types checking along the way for deeply nested attributes. Map<String, AttributeValue> addressesMap = personDocFromDb.getMapOfUnknownType("addresses"); addressesMap.keySet().forEach((String k) -> { logger.info("Looking at data for [{}] address", k); // Looking at data for [home] address AttributeValue value = addressesMap.get(k); AttributeValue cityValue = value.m().get("city"); if (cityValue != null) { logger.info(cityValue.s()); // Any Town } }); List<AttributeValue> phoneNumbers = personDocFromDb.getListOfUnknownType("phoneNumbers"); phoneNumbers.forEach((AttributeValue av) -> { if (av.hasM()) { AttributeValue type = av.m().get("type"); if (type.s() != null) { logger.info("Type of phone: {}", type.s()); // Type of phone: Home // Type of phone: Work } } }); String jsonPerson = personDocFromDb.toJson(); logger.info(jsonPerson); // {"firstName":"Shirley","lastName":"Rodriguez","addresses":{"home":{"zipCode":"00002","city":"Any Town","street":"123 Any Street","state":"ME"}},"hobbies":["Theater","Golf"], // "id":50,"nullAttribute":null,"age":53,"phoneNumbers":[{"number":"555-0140","type":"Home"},{"number":"555-0155","type":"Work"}]}

EnhancedDocument 实例可以与 DynamoDbTable 的任何方法或 DynamoDbEnhancedClient 结合使用来代替映射的数据类。