本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
在没有 DynamoDB 的情况下使用 EnhancedDocument
尽管您通常使用 EnhancedDocument
的实例来读取和写入文档类型的 DynamoDB 项目,但它也可以独立于 DynamoDB 使用。
您可以使用 EnhancedDocuments
的功能,在 JSON 字符串或自定义对象之间,执行到 AttributeValues
的低级映射的转换,如以下示例所示。
public static void conversionWithoutDynamoDbExample() { Address address = new Address(); address.setCity("my city"); address.setState("my state"); address.setStreet("my street"); address.setZipCode("00000"); // Build an EnhancedDocument instance for its conversion functionality alone. EnhancedDocument addressEnhancedDoc = EnhancedDocument.builder() // Important: You must specify attribute converter providers when you build an EnhancedDocument instance not used with a DynamoDB table. .attributeConverterProviders(new CustomAttributeConverterProvider(), DefaultAttributeConverterProvider.create()) .put("addressDoc", address, Address.class) .build(); // Convert address to a low-level item representation. final Map<String, AttributeValue> addressAsAttributeMap = addressEnhancedDoc.getMapOfUnknownType("addressDoc"); logger.info("addressAsAttributeMap: {}", addressAsAttributeMap.toString()); // Convert address to a JSON string. String addressAsJsonString = addressEnhancedDoc.getJson("addressDoc"); logger.info("addressAsJsonString: {}", addressAsJsonString); // Convert addressEnhancedDoc back to an Address instance. Address addressConverted = addressEnhancedDoc.get("addressDoc", Address.class); logger.info("addressConverted: {}", addressConverted.toString()); } /* Console output: addressAsAttributeMap: {zipCode=AttributeValue(S=00000), state=AttributeValue(S=my state), street=AttributeValue(S=my street), city=AttributeValue(S=my city)} addressAsJsonString: {"zipCode":"00000","state":"my state","street":"my street","city":"my city"} addressConverted: Address{street='my street', city='my city', state='my state', zipCode='00000'} */
注意
当您独立于 DynamoDB 表使用增强型文档时,请务必在生成器上明确设置属性转换器提供程序。
相比之下,当增强型文档与 DynamoDB 表结合使用时,文档表架构会提供转换器提供程序。