

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à.

# Esempio: operazioni Batch utilizzando l'API AWS SDK per Java dei documenti
<a name="batch-operation-document-api-java"></a>

Questa sezione fornisce esempi di operazioni di scrittura e acquisizione in batch in Amazon DynamoDB utilizzando AWS SDK per Java l'API Document.

**Nota**  
L'SDK per Java offre inoltre un modello di persistenza degli oggetti che permette di mappare le classi lato client alle tabelle DynamoDB. Questo approccio può ridurre la quantità di codice da scrivere. Per ulteriori informazioni, consulta [Java 1.x: Dinamo DBMapper](DynamoDBMapper.md).

**Topics**
+ [Esempio: operazione di scrittura in batch utilizzando l'API del AWS SDK per Java documento](#JavaDocumentAPIBatchWrite)
+ [Esempio: operazione Batch get utilizzando l'API del AWS SDK per Java documento](#JavaDocumentAPIBatchGet)

## Esempio: operazione di scrittura in batch utilizzando l'API del AWS SDK per Java documento
<a name="JavaDocumentAPIBatchWrite"></a>

Nel seguente esempio di codice Java viene utilizzato il metodo `batchWriteItem` per eseguire le seguenti operazioni di eliminazione e inserimento:
+ inserimento di un item nella tabella `Forum`;
+ Inserimento di un item ed eliminazione di un item dalla tabella `Thread`. 

Quando crei la tua risposta di scrittura in batch, puoi specificare qualsiasi quantità di richieste di inserimento ed eliminazione in una o più tabelle. Tuttavia, `batchWriteItem` limita la dimensione di una richiesta di scrittura in batch e il numero di operazioni di inserimento ed eliminazione in una singola operazione di scrittura in batch. Se la tua richiesta eccede questi limiti, essa verrà rigettata. Se la tua tabella non dispone di sufficiente throughput assegnato per soddisfare questa richiesta, gli elementi di richiesta non eseguiti vengono restituiti nella risposta. 

Il seguente esempio controlla la risposta nel caso in cui vi siano degli elementi di richiesta non eseguiti. Se sono presenti, esegue il loopback e invia nuovamente la richiesta `batchWriteItem` con gli elementi non elaborati della richiesta. Seguendo gli esempi presenti in questa guida dovrebbe essere già avvenuta la creazione delle tabelle `Forum` e `Thread`. Puoi anche creare queste tabelle e caricare i dati di esempio a livello di programmazione. Per ulteriori informazioni, consulta [Creazione di tabelle di esempio e caricamento di dati utilizzando AWS SDK per Java](AppendixSampleDataCodeJava.md).

Per step-by-step istruzioni su come testare il seguente esempio, vedere[Esempi di codice Java](CodeSamples.Java.md). 

**Example**  

```
package com.amazonaws.codesamples.document;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.BatchWriteItemOutcome;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.TableWriteItems;
import com.amazonaws.services.dynamodbv2.model.WriteRequest;

public class DocumentAPIBatchWrite {

    static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
    static DynamoDB dynamoDB = new DynamoDB(client);

    static String forumTableName = "Forum";
    static String threadTableName = "Thread";

    public static void main(String[] args) throws IOException {

        writeMultipleItemsBatchWrite();

    }

    private static void writeMultipleItemsBatchWrite() {
        try {

            // Add a new item to Forum
            TableWriteItems forumTableWriteItems = new TableWriteItems(forumTableName) // Forum
                    .withItemsToPut(new Item().withPrimaryKey("Name", "Amazon RDS").withNumber("Threads", 0));

            // Add a new item, and delete an existing item, from Thread
            // This table has a partition key and range key, so need to specify
            // both of them
            TableWriteItems threadTableWriteItems = new TableWriteItems(threadTableName)
                    .withItemsToPut(
                            new Item().withPrimaryKey("ForumName", "Amazon RDS", "Subject", "Amazon RDS Thread 1")
                                    .withString("Message", "ElastiCache Thread 1 message")
                                    .withStringSet("Tags", new HashSet<String>(Arrays.asList("cache", "in-memory"))))
                    .withHashAndRangeKeysToDelete("ForumName", "Subject", "Amazon S3", "S3 Thread 100");

            System.out.println("Making the request.");
            BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(forumTableWriteItems, threadTableWriteItems);

            do {

                // Check for unprocessed keys which could happen if you exceed
                // provisioned throughput

                Map<String, List<WriteRequest>> unprocessedItems = outcome.getUnprocessedItems();

                if (outcome.getUnprocessedItems().size() == 0) {
                    System.out.println("No unprocessed items found");
                } else {
                    System.out.println("Retrieving the unprocessed items");
                    outcome = dynamoDB.batchWriteItemUnprocessed(unprocessedItems);
                }

            } while (outcome.getUnprocessedItems().size() > 0);

        } catch (Exception e) {
            System.err.println("Failed to retrieve items: ");
            e.printStackTrace(System.err);
        }

    }

}
```

## Esempio: operazione Batch get utilizzando l'API del AWS SDK per Java documento
<a name="JavaDocumentAPIBatchGet"></a>

Nel seguente esempio di codice Java si utilizza il metodo `batchGetItem` per recuperare più item dalle tabelle `Forum` e `Thread`. L'item `BatchGetItemRequest` specifica i nomi delle tabelle e un elenco di chiavi per ogni item da ottenere. Nell'esempio si esegue la risposta stampando gli elementi recuperati.

**Nota**  
In questo esempio di codice si presuppone che i dati siano già stati caricati in DynamoDB per l'account seguendo le istruzioni riportate nella sezione [Creazione di tabelle e caricamento di dati per esempi di codice in DynamoDB](SampleData.md).  
Per step-by-step istruzioni su come eseguire l'esempio seguente, consulta[Esempi di codice Java](CodeSamples.Java.md).

**Example**  

```
package com.amazonaws.codesamples.document;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.BatchGetItemOutcome;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.TableKeysAndAttributes;
import com.amazonaws.services.dynamodbv2.model.KeysAndAttributes;

public class DocumentAPIBatchGet {
    static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
    static DynamoDB dynamoDB = new DynamoDB(client);

    static String forumTableName = "Forum";
    static String threadTableName = "Thread";

    public static void main(String[] args) throws IOException {
        retrieveMultipleItemsBatchGet();
    }

    private static void retrieveMultipleItemsBatchGet() {

        try {

            TableKeysAndAttributes forumTableKeysAndAttributes = new TableKeysAndAttributes(forumTableName);
            // Add a partition key
            forumTableKeysAndAttributes.addHashOnlyPrimaryKeys("Name", "Amazon S3", "Amazon DynamoDB");

            TableKeysAndAttributes threadTableKeysAndAttributes = new TableKeysAndAttributes(threadTableName);
            // Add a partition key and a sort key
            threadTableKeysAndAttributes.addHashAndRangePrimaryKeys("ForumName", "Subject", "Amazon DynamoDB",
                    "DynamoDB Thread 1", "Amazon DynamoDB", "DynamoDB Thread 2", "Amazon S3", "S3 Thread 1");

            System.out.println("Making the request.");

            BatchGetItemOutcome outcome = dynamoDB.batchGetItem(forumTableKeysAndAttributes,
                    threadTableKeysAndAttributes);

            Map<String, KeysAndAttributes> unprocessed = null;

            do {
                for (String tableName : outcome.getTableItems().keySet()) {
                    System.out.println("Items in table " + tableName);
                    List<Item> items = outcome.getTableItems().get(tableName);
                    for (Item item : items) {
                        System.out.println(item.toJSONPretty());
                    }
                }

                // Check for unprocessed keys which could happen if you exceed
                // provisioned
                // throughput or reach the limit on response size.
                unprocessed = outcome.getUnprocessedKeys();

                if (unprocessed.isEmpty()) {
                    System.out.println("No unprocessed keys found");
                } else {
                    System.out.println("Retrieving the unprocessed keys");
                    outcome = dynamoDB.batchGetItemUnprocessed(unprocessed);
                }

            } while (!unprocessed.isEmpty());

        } catch (Exception e) {
            System.err.println("Failed to retrieve items.");
            System.err.println(e.getMessage());
        }

    }

}
```