

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Lavora con documenti JSON con l'API Enhanced Document per DynamoDB
<a name="ddb-en-client-doc-api"></a>

L'[Enhanced Document API](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/enhanced/dynamodb/document/package-summary.html) for AWS SDK for Java 2.x è progettata per funzionare con dati orientati ai documenti che non hanno uno schema fisso. Tuttavia, consente anche di utilizzare classi personalizzate per mappare singoli attributi.

 L'Enhanced Document API è il successore dell'[API Document](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/document/DynamoDB.html) della AWS SDK per Java versione 1.x.

**Contents**
+ [Inizia a usare l'Enhanced Document API](ddb-en-client-doc-api-steps.md)
  + [Crea un e un `DocumentTableSchema` `DynamoDbTable`](ddb-en-client-doc-api-steps.md#ddb-en-client-doc-api-steps-createschema)
+ [Crea documenti avanzati](ddb-en-client-doc-api-steps-create-ed.md)
  + [Crea da una stringa JSON](ddb-en-client-doc-api-steps-create-ed.md#ddb-en-client-doc-api-steps-create-ed-fromJson)
  + [Costruisci a partire da singoli elementi](ddb-en-client-doc-api-steps-create-ed.md#ddb-en-client-doc-api-steps-create-ed-fromparts)
+ [Esegui operazioni CRUD](ddb-en-client-doc-api-steps-use.md)
+ [Accedi agli attributi avanzati del documento come oggetti personalizzati](ddb-en-client-doc-api-convert.md)
+ [Usa e `EnhancedDocument` senza DynamoDB](ddb-en-client-doc-api-standalone.md)

# Inizia a usare l'Enhanced Document API
<a name="ddb-en-client-doc-api-steps"></a>

L'API Enhanced Document richiede le stesse [dipendenze](ddb-en-client-getting-started.md#ddb-en-client-gs-dep) necessarie per l'API DynamoDB Enhanced Client. Richiede anche un'[`DynamoDbEnhancedClient`istanza](ddb-en-client-getting-started-dynamodbTable.md#ddb-en-client-getting-started-dynamodbTable-eclient), come mostrato all'inizio di questo argomento.

Poiché l'Enhanced Document API è stata rilasciata con la versione 2.20.3 di AWS SDK for Java 2.x, è necessaria quella versione o superiore.

## Crea un e un `DocumentTableSchema` `DynamoDbTable`
<a name="ddb-en-client-doc-api-steps-createschema"></a>

Per richiamare comandi su una tabella DynamoDB utilizzando l'API Enhanced Document, associa la tabella a un oggetto risorsa < > lato [DynamoDbTableclient EnhancedDocument](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/enhanced/dynamodb/DynamoDbTable.html). 

Il `table()` metodo del client avanzato crea un'`DynamoDbTable<EnhancedDocument>`istanza e richiede parametri per il nome della tabella DynamoDB e un. `DocumentTableSchema` 

Il builder for a [DocumentTableSchema](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/enhanced/dynamodb/document/DocumentTableSchema.html)richiede una chiave di indice principale e uno o più provider di convertitori di attributi. Il `AttributeConverterProvider.defaultProvider()` metodo fornisce convertitori per i tipi [predefiniti](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/enhanced/dynamodb/internal/converter/attribute/package-summary.html). Dovrebbe essere specificato anche se si fornisce un provider di convertitori di attributi personalizzato. È possibile aggiungere una chiave di indice secondaria opzionale al generatore.

Il seguente frammento di codice mostra il codice che genera la rappresentazione lato client di una tabella DynamoDB che memorizza oggetti senza schema. `person` `EnhancedDocument`

```
DynamoDbTable<EnhancedDocument> documentDynamoDbTable = 
                enhancedClient.table("person",
                        TableSchema.documentSchemaBuilder()
                            // Specify the primary key attributes.
                            .addIndexPartitionKey(TableMetadata.primaryIndexName(),"id", AttributeValueType.S)
                            .addIndexSortKey(TableMetadata.primaryIndexName(), "lastName", AttributeValueType.S)
                            // Specify attribute converter providers. Minimally add the default one.
                            .attributeConverterProviders(AttributeConverterProvider.defaultProvider())
                            .build());
                                                         
// Call documentTable.createTable() if "person" does not exist in DynamoDB.
// createTable() should be called only one time.
```

Di seguito viene illustrata la rappresentazione JSON di un oggetto utilizzata in questa sezione. `person`

### Oggetto JSON `person`
<a name="ddb-en-client-doc-api-steps-createschema-obj"></a>

```
{
  "id": 1,
  "firstName": "Richard",
  "lastName": "Roe",
  "age": 25,
  "addresses":
    {
      "home": {
        "zipCode": "00000",
        "city": "Any Town",
        "state": "FL",
        "street": "123 Any Street"
      },
      "work": {
        "zipCode": "00001",
        "city": "Anywhere",
        "state": "FL",
        "street": "100 Main Street"
      }
    },
  "hobbies": [
    "Hobby 1",
    "Hobby 2"
  ],
  "phoneNumbers": [
    {
      "type": "Home",
      "number": "555-0100"
    },
    {
      "type": "Work",
      "number": "555-0119"
    }
  ]
}
```

# Crea documenti avanzati
<a name="ddb-en-client-doc-api-steps-create-ed"></a>

An `[EnhancedDocument](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/enhanced/dynamodb/document/EnhancedDocument.html)` rappresenta un oggetto di tipo documento con una struttura complessa con attributi annidati. An `EnhancedDocument` richiede attributi di primo livello che corrispondano agli attributi della chiave primaria specificati per. `DocumentTableSchema` Il contenuto rimanente è arbitrario e può essere costituito da attributi di primo livello e anche da attributi profondamente annidati.

Si crea un'`EnhancedDocument`istanza utilizzando un generatore che offre diversi modi per aggiungere elementi.

## Crea da una stringa JSON
<a name="ddb-en-client-doc-api-steps-create-ed-fromJson"></a>

Con una stringa JSON, puoi creare una chiamata `EnhancedDocument` in un unico metodo. Il seguente frammento crea un `EnhancedDocument` da una stringa JSON restituita dal metodo helper. `jsonPerson()` [Il `jsonPerson()` metodo restituisce la versione in stringa JSON dell'oggetto persona mostrato in precedenza.](ddb-en-client-doc-api-steps.md#ddb-en-client-doc-api-steps-createschema-obj)

```
EnhancedDocument document = 
        EnhancedDocument.builder()
                        .json( jsonPerson() )
                        .build());
```

## Costruisci a partire da singoli elementi
<a name="ddb-en-client-doc-api-steps-create-ed-fromparts"></a>

In alternativa, puoi creare un'`EnhancedDocument`istanza a partire da singoli componenti utilizzando i metodi type-safe del builder.

L'esempio seguente crea un documento `person` avanzato simile al documento avanzato creato a partire dalla stringa JSON dell'esempio precedente.

```
        /* Define the shape of an address map whose JSON representation looks like the following.
           Use 'addressMapEnhancedType' in the following EnhancedDocument.builder() to simplify the code.
           "home": {
             "zipCode": "00000",
             "city": "Any Town",
             "state": "FL",
             "street": "123 Any Street"
           }*/
        EnhancedType<Map<String, String>> addressMapEnhancedType =
                EnhancedType.mapOf(EnhancedType.of(String.class), EnhancedType.of(String.class));


        //  Use the builder's typesafe methods to add elements to the enhanced document.
        EnhancedDocument personDocument = EnhancedDocument.builder()
                .putNumber("id", 50)
                .putString("firstName", "Shirley")
                .putString("lastName", "Rodriguez")
                .putNumber("age", 53)
                .putNull("nullAttribute")
                .putJson("phoneNumbers", phoneNumbersJSONString())
                /* Add the map of addresses whose JSON representation looks like the following.
                        {
                          "home": {
                            "zipCode": "00000",
                            "city": "Any Town",
                            "state": "FL",
                            "street": "123 Any Street"
                          }
                        } */
                .putMap("addresses", getAddresses(), EnhancedType.of(String.class), addressMapEnhancedType)
                .putList("hobbies", List.of("Theater", "Golf"), EnhancedType.of(String.class))
                .build();
```

### Metodi di supporto
<a name="ddb-en-client-doc-api-steps-use-fromparts-helpers"></a>

```
    private static String phoneNumbersJSONString() {
        return "  [" +
                "    {" +
                "      \"type\": \"Home\"," +
                "      \"number\": \"555-0140\"" +
                "    }," +
                "    {" +
                "      \"type\": \"Work\"," +
                "      \"number\": \"555-0155\"" +
                "    }" +
                "  ]";
    }

    private static Map<String, Map<String, String>> getAddresses() {
        return Map.of(
                "home", Map.of(
                        "zipCode", "00002",
                        "city", "Any Town",
                        "state", "ME",
                        "street", "123 Any Street"));

    }
```

# Esegui operazioni CRUD
<a name="ddb-en-client-doc-api-steps-use"></a>

Dopo aver definito un'`EnhancedDocument`istanza, è possibile salvarla in una tabella DynamoDB. Il seguente frammento di codice utilizza [PersonDocument creato](ddb-en-client-doc-api-steps-create-ed.md#ddb-en-client-doc-api-steps-create-ed-fromparts) da singoli elementi.

```
documentDynamoDbTable.putItem(personDocument);
```

Dopo aver letto un'istanza di documento avanzata da DynamoDB, è possibile estrarre i valori dei singoli attributi utilizzando i getter, come mostrato nel seguente frammento di codice, che accedono ai dati salvati da. `personDocument` In alternativa, è possibile estrarre il contenuto completo in una stringa JSON, come mostrato nell'ultima parte del codice di esempio.

```
        // 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`le istanze possono essere utilizzate con qualsiasi metodo `[DynamoDbTable](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/enhanced/dynamodb/DynamoDbTable.html)` o al posto delle classi [DynamoDbEnhancedClient](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/enhanced/dynamodb/DynamoDbEnhancedClient.html)di dati mappate.

# Accedi agli attributi avanzati del documento come oggetti personalizzati
<a name="ddb-en-client-doc-api-convert"></a>

Oltre a fornire un'API per leggere e scrivere attributi con strutture senza schema, l'API Enhanced Document consente di convertire gli attributi da e verso istanze di classi personalizzate.

L'API Enhanced Document utilizza `AttributeConverterProvider` i `AttributeConverter` caratteri e i caratteri mostrati nella sezione di [conversione degli attributi di controllo](ddb-en-client-adv-features-conversion.md) come parte dell'API DynamoDB Enhanced Client.

Nell'esempio seguente, utilizziamo a `CustomAttributeConverterProvider` con la sua `AddressConverter` classe annidata per convertire gli oggetti. `Address` 

Questo esempio mostra che è possibile combinare dati provenienti da classi e anche dati provenienti da strutture create secondo necessità. Questo esempio mostra anche che le classi personalizzate possono essere utilizzate a qualsiasi livello di una struttura annidata. Gli `Address` oggetti in questo esempio sono valori utilizzati in una mappa.

```
    public static void attributeToAddressClassMappingExample(DynamoDbEnhancedClient enhancedClient, DynamoDbClient standardClient) {
        String tableName = "customer";

        // Define the DynamoDbTable for an enhanced document.
        // The schema builder provides methods for attribute converter providers and keys.
        DynamoDbTable<EnhancedDocument> documentDynamoDbTable = enhancedClient.table(tableName,
                DocumentTableSchema.builder()
                        // Add the CustomAttributeConverterProvider along with the default when you build the table schema.
                        .attributeConverterProviders(
                                List.of(
                                        new CustomAttributeConverterProvider(),
                                        AttributeConverterProvider.defaultProvider()))
                        .addIndexPartitionKey(TableMetadata.primaryIndexName(), "id", AttributeValueType.N)
                        .addIndexSortKey(TableMetadata.primaryIndexName(), "lastName", AttributeValueType.S)
                        .build());
        // Create the DynamoDB table if needed.
        documentDynamoDbTable.createTable();
        waitForTableCreation(tableName, standardClient);


        // The getAddressesForCustomMappingExample() helper method that provides 'addresses' shows the use of a custom Address class
        // rather than using a Map<String, Map<String, String> to hold the address data.
        Map<String, Address> addresses = getAddressesForCustomMappingExample();

        // Build an EnhancedDocument instance to save an item with a mix of structures defined as needed and static classes.
        EnhancedDocument personDocument = EnhancedDocument.builder()
                .putNumber("id", 50)
                .putString("firstName", "Shirley")
                .putString("lastName", "Rodriguez")
                .putNumber("age", 53)
                .putNull("nullAttribute")
                .putJson("phoneNumbers", phoneNumbersJSONString())
                // Note the use of 'EnhancedType.of(Address.class)' instead of the more generic
                // 'EnhancedType.mapOf(EnhancedType.of(String.class), EnhancedType.of(String.class))' that was used in a previous example.
                .putMap("addresses", addresses, EnhancedType.of(String.class), EnhancedType.of(Address.class))
                .putList("hobbies", List.of("Hobby 1", "Hobby 2"), EnhancedType.of(String.class))
                .build();
        // Save the item to DynamoDB.
        documentDynamoDbTable.putItem(personDocument);

        // Retrieve the item just saved.
        EnhancedDocument srPerson = documentDynamoDbTable.getItem(Key.builder().partitionValue(50).sortValue("Rodriguez").build());

        // Access the addresses attribute.
        Map<String, Address> srAddresses = srPerson.get("addresses",
                EnhancedType.mapOf(EnhancedType.of(String.class), EnhancedType.of(Address.class)));

        srAddresses.keySet().forEach(k -> logger.info(addresses.get(k).toString()));

        documentDynamoDbTable.deleteTable();

// The content logged to the console shows that the saved maps were converted to Address instances.
Address{street='123 Main Street', city='Any Town', state='NC', zipCode='00000'}
Address{street='100 Any Street', city='Any Town', state='NC', zipCode='00000'}
```

## Codice `CustomAttributeConverterProvider`
<a name="ddb-en-client-doc-api-convert-provider"></a>

```
public class CustomAttributeConverterProvider implements AttributeConverterProvider {

    private final Map<EnhancedType<?>, AttributeConverter<?>> converterCache = ImmutableMap.of(
            // 1. Add AddressConverter to the internal cache.
            EnhancedType.of(Address.class), new AddressConverter());

    public static CustomAttributeConverterProvider create() {
        return new CustomAttributeConverterProvider();
    }

    // 2. The enhanced client queries the provider for attribute converters if it
    //    encounters a type that it does not know how to convert.
    @SuppressWarnings("unchecked")
    @Override
    public <T> AttributeConverter<T> converterFor(EnhancedType<T> enhancedType) {
        return (AttributeConverter<T>) converterCache.get(enhancedType);
    }

    // 3. Custom attribute converter
    private class AddressConverter implements AttributeConverter<Address> {
        // 4. Transform an Address object into a DynamoDB map.
        @Override
        public AttributeValue transformFrom(Address address) {

            Map<String, AttributeValue> attributeValueMap = Map.of(
                    "street", AttributeValue.fromS(address.getStreet()),
                    "city", AttributeValue.fromS(address.getCity()),
                    "state", AttributeValue.fromS(address.getState()),
                    "zipCode", AttributeValue.fromS(address.getZipCode()));

            return AttributeValue.fromM(attributeValueMap);
        }

        // 5. Transform the DynamoDB map attribute to an Address oject.
        @Override
        public Address transformTo(AttributeValue attributeValue) {
            Map<String, AttributeValue> m = attributeValue.m();
            Address address = new Address();
            address.setStreet(m.get("street").s());
            address.setCity(m.get("city").s());
            address.setState(m.get("state").s());
            address.setZipCode(m.get("zipCode").s());

            return address;
        }

        @Override
        public EnhancedType<Address> type() {
            return EnhancedType.of(Address.class);
        }

        @Override
        public AttributeValueType attributeValueType() {
            return AttributeValueType.M;
        }
    }
}
```

## Classe `Address`
<a name="ddb-en-client-doc-api-convert-address"></a>

```
public class Address {
                  private String street;
                  private String city;
                  private String state;
                  private String zipCode;

                  public Address() {
                  }

                  public String getStreet() {
                  return this.street;
                  }

                  public String getCity() {
                  return this.city;
                  }

                  public String getState() {
                  return this.state;
                  }

                  public String getZipCode() {
                  return this.zipCode;
                  }

                  public void setStreet(String street) {
                  this.street = street;
                  }

                  public void setCity(String city) {
                  this.city = city;
                  }

                  public void setState(String state) {
                  this.state = state;
                  }

                  public void setZipCode(String zipCode) {
                  this.zipCode = zipCode;
                  }
                  }
```

## Metodo di supporto che fornisce indirizzi
<a name="ddb-en-client-doc-api-convert-helper"></a>

Il seguente metodo di supporto fornisce la mappa che utilizza istanze personalizzate per i valori anziché `Address` istanze generiche `Map<String, String>` per i valori.

```
    private static Map<String, Address> getAddressesForCustomMappingExample() {
        Address homeAddress = new Address();
        homeAddress.setStreet("100 Any Street");
        homeAddress.setCity("Any Town");
        homeAddress.setState("NC");
        homeAddress.setZipCode("00000");

        Address workAddress = new Address();
        workAddress.setStreet("123 Main Street");
        workAddress.setCity("Any Town");
        workAddress.setState("NC");
        workAddress.setZipCode("00000");

        return Map.of("home", homeAddress,
                "work", workAddress);
    }
```

# Usa e `EnhancedDocument` senza DynamoDB
<a name="ddb-en-client-doc-api-standalone"></a>

Sebbene di solito si utilizzi un'istanza di an `EnhancedDocument` per leggere e scrivere elementi DynamoDB di tipo documento, può essere utilizzata anche indipendentemente da DynamoDB. 

È possibile utilizzarli `EnhancedDocuments` per la loro capacità di convertire tra stringhe JSON o oggetti personalizzati in mappe di basso livello come mostrato nell'esempio seguente. `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'}
   */
```

**Nota**  
Quando utilizzi un documento avanzato indipendente da una tabella DynamoDB, assicurati di impostare in modo esplicito i provider di conversione degli attributi sul builder.  
Al contrario, lo schema della tabella dei documenti fornisce i provider di conversione quando un documento avanzato viene utilizzato con una tabella DynamoDB.