

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

# Utilizzo degli elementi: Java
<a name="JavaDocumentAPIItemCRUD"></a>

Puoi utilizzare l'API AWS SDK per Java Document per eseguire operazioni tipiche di creazione, lettura, aggiornamento ed eliminazione (CRUD) sugli elementi di Amazon DynamoDB in una tabella.

**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).

Questa sezione contiene esempi Java per eseguire diverse operazioni operazioni sugli elementi dell'API documento Java e diversi esempi di lavoro completi.

**Topics**
+ [Collocazione di un elemento](#PutDocumentAPIJava)
+ [Ottenimento di un elemento](#JavaDocumentAPIGetItem)
+ [Scrittura in batch: collocazione ed eliminazione di più elementi](#BatchWriteDocumentAPIJava)
+ [Ricezione in batch: ricezione di più elementi](#JavaDocumentAPIBatchGetItem)
+ [Aggiornamento di un elemento](#JavaDocumentAPIItemUpdate)
+ [Eliminazione di un elemento](#DeleteMidLevelJava)
+ [Esempio: operazioni CRUD che utilizzano l'API del documento AWS SDK per Java](JavaDocumentAPICRUDExample.md)
+ [Esempio: operazioni Batch utilizzando l'API AWS SDK per Java dei documenti](batch-operation-document-api-java.md)
+ [Esempio: gestione degli attributi di tipo binario utilizzando l'API del AWS SDK per Java documento](JavaDocumentAPIBinaryTypeExample.md)

## Collocazione di un elemento
<a name="PutDocumentAPIJava"></a>

Il metodo `putItem` memorizza un item nella tabella. Se l'item esiste, lo sostituisce per intero. Se invece di sostituire l'intero item vuoi aggiornare solo attributi specifici, puoi utilizzare il metodo `updateItem`. Per ulteriori informazioni, consulta [Aggiornamento di un elemento](#JavaDocumentAPIItemUpdate). 

------
#### [ Java v2 ]

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import java.util.HashMap;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * To place items into an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client. See the EnhancedPutItem example.
 */
public class PutItem {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <key> <keyVal> <albumtitle> <albumtitleval> <awards> <awardsval> <Songtitle> <songtitleval>

                Where:
                    tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3).
                    key - The key used in the Amazon DynamoDB table (for example, Artist).
                    keyval - The key value that represents the item to get (for example, Famous Band).
                    albumTitle - The Album title (for example, AlbumTitle).
                    AlbumTitleValue - The name of the album (for example, Songs About Life ).
                    Awards - The awards column (for example, Awards).
                    AwardVal - The value of the awards (for example, 10).
                    SongTitle - The song title (for example, SongTitle).
                    SongTitleVal - The value of the song title (for example, Happy Day).
                **Warning** This program will  place an item that you specify into a table!
                """;

        if (args.length != 9) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String key = args[1];
        String keyVal = args[2];
        String albumTitle = args[3];
        String albumTitleValue = args[4];
        String awards = args[5];
        String awardVal = args[6];
        String songTitle = args[7];
        String songTitleVal = args[8];

        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        putItemInTable(ddb, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle,
                songTitleVal);
        System.out.println("Done!");
        ddb.close();
    }

    public static void putItemInTable(DynamoDbClient ddb,
            String tableName,
            String key,
            String keyVal,
            String albumTitle,
            String albumTitleValue,
            String awards,
            String awardVal,
            String songTitle,
            String songTitleVal) {

        HashMap<String, AttributeValue> itemValues = new HashMap<>();
        itemValues.put(key, AttributeValue.builder().s(keyVal).build());
        itemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build());
        itemValues.put(albumTitle, AttributeValue.builder().s(albumTitleValue).build());
        itemValues.put(awards, AttributeValue.builder().s(awardVal).build());

        PutItemRequest request = PutItemRequest.builder()
                .tableName(tableName)
                .item(itemValues)
                .build();

        try {
            PutItemResponse response = ddb.putItem(request);
            System.out.println(tableName + " was successfully updated. The request id is "
                    + response.responseMetadata().requestId());

        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            System.err.println("Be sure that it exists and that you've typed its name correctly!");
            System.exit(1);
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```

------
#### [ Java v1 ]

Completare la procedura riportata di seguito. 

1. Creare un'istanza della classe `DynamoDB`.

1. Crea un'istanza della classe `Table` per rappresentare la tabella con cui vuoi lavorare.

1. Crea un'istanza della classe `Item` per rappresentare il nuovo item. Devi specificare la chiave primaria del nuovo item e gli attributi.

1. Chiama il metodo `putItem` dell'oggetto `Table` usando l'elemento `Item` creato nella fase precedente.

Il seguente esempio di codice Java mostra le attività precedenti. Il codice scrive un nuovo item nella tabella `ProductCatalog`.

**Example**  

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

Table table = dynamoDB.getTable("ProductCatalog");

// Build a list of related items
List<Number> relatedItems = new ArrayList<Number>();
relatedItems.add(341);
relatedItems.add(472);
relatedItems.add(649);

//Build a map of product pictures
Map<String, String> pictures = new HashMap<String, String>();
pictures.put("FrontView", "http://example.com/products/123_front.jpg");
pictures.put("RearView", "http://example.com/products/123_rear.jpg");
pictures.put("SideView", "http://example.com/products/123_left_side.jpg");

//Build a map of product reviews
Map<String, List<String>> reviews = new HashMap<String, List<String>>();

List<String> fiveStarReviews = new ArrayList<String>();
fiveStarReviews.add("Excellent! Can't recommend it highly enough!  Buy it!");
fiveStarReviews.add("Do yourself a favor and buy this");
reviews.put("FiveStar", fiveStarReviews);

List<String> oneStarReviews = new ArrayList<String>();
oneStarReviews.add("Terrible product!  Do not buy this.");
reviews.put("OneStar", oneStarReviews);

// Build the item
Item item = new Item()
    .withPrimaryKey("Id", 123)
    .withString("Title", "Bicycle 123")
    .withString("Description", "123 description")
    .withString("BicycleType", "Hybrid")
    .withString("Brand", "Brand-Company C")
    .withNumber("Price", 500)
    .withStringSet("Color",  new HashSet<String>(Arrays.asList("Red", "Black")))
    .withString("ProductCategory", "Bicycle")
    .withBoolean("InStock", true)
    .withNull("QuantityOnHand")
    .withList("RelatedItems", relatedItems)
    .withMap("Pictures", pictures)
    .withMap("Reviews", reviews);

// Write the item to the table
PutItemOutcome outcome = table.putItem(item);
```

Nell'esempio precedente, l'item ha attributi scalari (`String`, `Number`, `Boolean`, `Null`), set (`String Set`) e tipi di documento (`List`, `Map`).

------

### Specifica dei parametri facoltativi
<a name="PutItemJavaDocumentAPIOptions"></a>

Insieme ai parametri richiesti, puoi anche specificare parametri opzionali per il metodo `putItem`. Ad esempio, il seguente esempio di codice Java utilizza un parametro facoltativo per specificare una condizione per il caricamento dell'item. Se la condizione specificata non è soddisfatta, genera un. AWS SDK per Java `ConditionalCheckFailedException` L'esempio di codice specifica i seguenti parametri facoltativi nel metodo `putItem`:
+ un item `ConditionExpression` che definisce le condizioni della richiesta. Il codice definisce la condizione in cui l'item esistente che ha la stessa chiave primaria viene sostituito solo se ha un attributo ISBN uguale a un valore specifico. 
+ Una mappa per `ExpressionAttributeValues` che viene usata nella condizione. In questo caso, è necessaria una sola sostituzione: il segnaposto `:val` nell'espressione della condizione viene sostituito al runtime con il valore ISBN effettivo da verificare.

Nell'esempio seguente viene aggiunto un nuovo item del libro utilizzando questi parametri facoltativi.

**Example**  

```
Item item = new Item()
    .withPrimaryKey("Id", 104)
    .withString("Title", "Book 104 Title")
    .withString("ISBN", "444-4444444444")
    .withNumber("Price", 20)
    .withStringSet("Authors",
        new HashSet<String>(Arrays.asList("Author1", "Author2")));

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val", "444-4444444444");

PutItemOutcome outcome = table.putItem(
    item,
    "ISBN = :val", // ConditionExpression parameter
    null,          // ExpressionAttributeNames parameter - we're not using it for this example
    expressionAttributeValues);
```

### PutItem e documenti JSON
<a name="PutItemJavaDocumentAPI.JSON"></a>

È possibile memorizzare un documento JSON come attributo in una tabella DynamoDB. Per eseguire questa operazione, usa il metodo `withJSON` di `Item`. Questo metodo analizza il documento JSON e mappa ciascun elemento a un tipo di dati DynamoDB nativo.

Supponiamo di voler memorizzare il seguente documento JSON, contenente i fornitori in grado di soddisfare gli ordini di un determinato prodotto.

**Example**  

```
{
    "V01": {
        "Name": "Acme Books",
        "Offices": [ "Seattle" ]
    },
    "V02": {
        "Name": "New Publishers, Inc.",
        "Offices": ["London", "New York"
        ]
    },
    "V03": {
        "Name": "Better Buy Books",
        "Offices": [ "Tokyo", "Los Angeles", "Sydney"
        ]
    }
}
```

Puoi utilizzare il metodo `withJSON` per memorizzarlo nella tabella `ProductCatalog`, in un attributo `Map` denominato `VendorInfo`. Il seguente codice di esempio Java dimostra come eseguire questa operazione.

```
// Convert the document into a String.  Must escape all double-quotes.
String vendorDocument = "{"
    + "    \"V01\": {"
    + "        \"Name\": \"Acme Books\","
    + "        \"Offices\": [ \"Seattle\" ]"
    + "    },"
    + "    \"V02\": {"
    + "        \"Name\": \"New Publishers, Inc.\","
    + "        \"Offices\": [ \"London\", \"New York\"" + "]" + "},"
    + "    \"V03\": {"
    + "        \"Name\": \"Better Buy Books\","
    +          "\"Offices\": [ \"Tokyo\", \"Los Angeles\", \"Sydney\""
    + "            ]"
    + "        }"
    + "    }";

Item item = new Item()
    .withPrimaryKey("Id", 210)
    .withString("Title", "Book 210 Title")
    .withString("ISBN", "210-2102102102")
    .withNumber("Price", 30)
    .withJSON("VendorInfo", vendorDocument);

PutItemOutcome outcome = table.putItem(item);
```

## Ottenimento di un elemento
<a name="JavaDocumentAPIGetItem"></a>

Per recuperare un singolo item usa il metodo `getItem` di un oggetto `Table`. Completare la procedura riportata di seguito. 

1. Creare un'istanza della classe `DynamoDB`.

1. Crea un'istanza della classe `Table` per rappresentare la tabella con cui vuoi lavorare.

1. Chiama il metodo `getItem` dell'istanza di `Table`. Devi specificare la chiave primaria dell'item che intendi recuperare.

Il seguente esempio di codice Java mostra le fasi precedenti. Il codice ottiene l'item che ha la chiave di partizione specificata.

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

Table table = dynamoDB.getTable("ProductCatalog");

Item item = table.getItem("Id", 210);
```

### Specifica dei parametri facoltativi
<a name="GetItemJavaDocumentAPIOptions"></a>

Insieme ai parametri richiesti, puoi anche specificare parametri opzionali per il metodo `getItem`. Ad esempio, il seguente esempio di codice Java utilizza un metodo facoltativo per recuperare un solo elenco specifico di attributi e per specificare letture fortemente consistenti. Per ulteriori informazioni sulla lettura consistente, consulta [Coerenza di lettura di DynamoDB](HowItWorks.ReadConsistency.md).

Puoi usare un `ProjectionExpression` per recuperare solo attributi o elementi specifici, piuttosto che un intero item. Un `ProjectionExpression` può specificare attributi nidificati o di primo livello usando i percorsi dei documenti. Per ulteriori informazioni, consulta [Utilizzo di espressioni di proiezione in DynamoDB](Expressions.ProjectionExpressions.md).

I parametri del metodo `getItem` non consentono di specificare lettura coerente. Tuttavia, puoi creare un `GetItemSpec`, che fornisce l'accesso completo a tutti gli input all'operazione `GetItem` di basso livello. Il seguente esempio di codice consente di creare un `GetItemSpec` e utilizzare tale specifica come input per il metodo `getItem`.

**Example**  

```
GetItemSpec spec = new GetItemSpec()
    .withPrimaryKey("Id", 206)
    .withProjectionExpression("Id, Title, RelatedItems[0], Reviews.FiveStar")
    .withConsistentRead(true);

Item item = table.getItem(spec);

System.out.println(item.toJSONPretty());
```

 Per stampare un `Item` in un formato leggibile, utilizza il metodo `toJSONPretty`. L'aspetto dell'output dall'esempio precedente è simile al seguente.

```
{
  "RelatedItems" : [ 341 ],
  "Reviews" : {
    "FiveStar" : [ "Excellent! Can't recommend it highly enough! Buy it!", "Do yourself a favor and buy this" ]
  },
  "Id" : 123,
  "Title" : "20-Bicycle 123"
}
```

### GetItem e documenti JSON
<a name="GetItemJavaDocumentAPI.JSON"></a>

Nella sezione [PutItem e documenti JSON](#PutItemJavaDocumentAPI.JSON), viene archiviato un documento JSON in un attributo `Map` denominato `VendorInfo`. Puoi utilizzare il metodo `getItem` per recuperare l'intero documento nel formato JSON. Oppure puoi utilizzare la notazione del percorso del documento per recuperare solo gli stessi elementi nel documento. Il seguente esempio di codice Java mostra queste tecniche.

```
GetItemSpec spec = new GetItemSpec()
    .withPrimaryKey("Id", 210);

System.out.println("All vendor info:");
spec.withProjectionExpression("VendorInfo");
System.out.println(table.getItem(spec).toJSON());

System.out.println("A single vendor:");
spec.withProjectionExpression("VendorInfo.V03");
System.out.println(table.getItem(spec).toJSON());

System.out.println("First office location for this vendor:");
spec.withProjectionExpression("VendorInfo.V03.Offices[0]");
System.out.println(table.getItem(spec).toJSON());
```

L'aspetto dell'output dall'esempio precedente è simile al seguente.

```
All vendor info:
{"VendorInfo":{"V03":{"Name":"Better Buy Books","Offices":["Tokyo","Los Angeles","Sydney"]},"V02":{"Name":"New Publishers, Inc.","Offices":["London","New York"]},"V01":{"Name":"Acme Books","Offices":["Seattle"]}}}
A single vendor:
{"VendorInfo":{"V03":{"Name":"Better Buy Books","Offices":["Tokyo","Los Angeles","Sydney"]}}}
First office location for a single vendor:
{"VendorInfo":{"V03":{"Offices":["Tokyo"]}}}
```

**Nota**  
Puoi usare il metodo `toJSON` per convertire qualsiasi item (o gli attributi) in una stringa in formato JSON. Il seguente codice recupera diversi attributi di primo livello e nidificati e stampa i risultati come JSON.  

```
GetItemSpec spec = new GetItemSpec()
    .withPrimaryKey("Id", 210)
    .withProjectionExpression("VendorInfo.V01, Title, Price");

Item item = table.getItem(spec);
System.out.println(item.toJSON());
```
L'output sarà simile al seguente.  

```
{"VendorInfo":{"V01":{"Name":"Acme Books","Offices":["Seattle"]}},"Price":30,"Title":"Book 210 Title"}
```

## Scrittura in batch: collocazione ed eliminazione di più elementi
<a name="BatchWriteDocumentAPIJava"></a>

La *scrittura in batch* fa riferimento alla collocazione e all'eliminazione di più item in un batch. Il metodo `batchWriteItem` ti consente di inserire ed eliminare più item da una o più tabelle con un'unica chiamata. Di seguito sono riportati i passaggi per inserire o eliminare più elementi utilizzando l'API AWS SDK per Java Document.

1. Creare un'istanza della classe `DynamoDB`.

1. Crea un'istanza della classe `TableWriteItems` che descrive tutte le operazioni di inserimento ed eliminazione per una tabella. Se vuoi scrivere su più tabelle in una sola operazione di scrittura in batch, devi creare un'istanza di `TableWriteItems` per tabella.

1. Chiama il metodo `batchWriteItem` fornendo gli oggetti `TableWriteItems` creati nella fase precedente. 

1. Elabora la risposta. Dovresti controllare se erano presenti item di richiesta non elaborati restituiti nella risposta. Questo potrebbe accadere se raggiungi la quota di throughput assegnata o si verifica un altro errore transitorio. Inoltre, DynamoDB limita la dimensione della richiesta e il numero di operazioni che possono essere specificate in una richiesta. Se si superano questi limiti, DynamoDB rifiuta la richiesta. Per ulteriori informazioni, consulta [Quote in Amazon DynamoDB](ServiceQuotas.md). 

Il seguente esempio di codice Java mostra le fasi precedenti. L'esempio esegue un'operazione `batchWriteItem` su due tabelle: `Forum` e `Thread`. Gli oggetti `TableWriteItems` corrispondenti definiscono le operazioni seguenti:
+ inserimento di un item nella tabella `Forum`.
+ Inserimento ed eliminazione di un item nella tabella `Thread`.

Il codice quindi chiama `batchWriteItem` per eseguire l'operazione.

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

TableWriteItems forumTableWriteItems = new TableWriteItems("Forum")
    .withItemsToPut(
        new Item()
            .withPrimaryKey("Name", "Amazon RDS")
            .withNumber("Threads", 0));

TableWriteItems threadTableWriteItems = new TableWriteItems("Thread")
    .withItemsToPut(
        new Item()
            .withPrimaryKey("ForumName","Amazon RDS","Subject","Amazon RDS Thread 1")
    .withHashAndRangeKeysToDelete("ForumName","Some partition key value", "Amazon S3", "Some sort key value");

BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(forumTableWriteItems, threadTableWriteItems);

// Code for checking unprocessed items is omitted in this example
```

Per un esempio di utilizzo, consulta [Esempio: operazione di scrittura in batch utilizzando l'API del AWS SDK per Java documento](batch-operation-document-api-java.md#JavaDocumentAPIBatchWrite). 

## Ricezione in batch: ricezione di più elementi
<a name="JavaDocumentAPIBatchGetItem"></a>

Il metodo `batchGetItem` ti consente di recuperare più item da una o più tabelle. Per recuperare un singolo item puoi usare il metodo `getItem`. 

Completare la procedura riportata di seguito. 

1. Creare un'istanza della classe `DynamoDB`.

1. Crea un'istanza della classe `TableKeysAndAttributes` e descrivi un elenco di valori delle chiavi primarie da recuperare da una tabella. Se vuoi leggere da più tabelle in una sola operazione Get in batch, devi creare un'istanza di `TableKeysAndAttributes` per tabella.

1. Chiama il metodo `batchGetItem` fornendo gli oggetti `TableKeysAndAttributes` creati nella fase precedente.

Il seguente esempio di codice Java mostra le fasi precedenti. L'esempio consente di recuperare due item dalla tabella `Forum` e tre item dalla tabella `Thread`.

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

    TableKeysAndAttributes forumTableKeysAndAttributes = new TableKeysAndAttributes(forumTableName);
    forumTableKeysAndAttributes.addHashOnlyPrimaryKeys("Name",
    "Amazon S3",
    "Amazon DynamoDB");

TableKeysAndAttributes threadTableKeysAndAttributes = new TableKeysAndAttributes(threadTableName);
threadTableKeysAndAttributes.addHashAndRangePrimaryKeys("ForumName", "Subject",
    "Amazon DynamoDB","DynamoDB Thread 1",
    "Amazon DynamoDB","DynamoDB Thread 2",
    "Amazon S3","S3 Thread 1");

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

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);
    }
}
```

### Specifica dei parametri facoltativi
<a name="BatchGetItemJavaDocumentAPIOptions"></a>

Insieme ai parametri richiesti, puoi anche specificare parametri opzionali usando `batchGetItem`. Puoi ad esempio fornire un `ProjectionExpression` con ogni `TableKeysAndAttributes` che definisci. Ciò ti consente di specificare gli attributi che vuoi recuperare dalla tabella.

L'esempio di codice seguente recupera due item dalla tabella `Forum`. Il parametro `withProjectionExpression` specifica che deve essere recuperato solo l'attributo `Threads`.

**Example**  

```
TableKeysAndAttributes forumTableKeysAndAttributes = new TableKeysAndAttributes("Forum")
    .withProjectionExpression("Threads");

forumTableKeysAndAttributes.addHashOnlyPrimaryKeys("Name",
    "Amazon S3",
    "Amazon DynamoDB");

BatchGetItemOutcome outcome = dynamoDB.batchGetItem(forumTableKeysAndAttributes);
```

## Aggiornamento di un elemento
<a name="JavaDocumentAPIItemUpdate"></a>

Il metodo `updateItem` di un oggetto `Table` può aggiornare i valori degli attributi esistenti, aggiungere nuovi attributi o eliminare attributi da un item esistente. 

Il metodo `updateItem` si comporta nel modo seguente:
+ Se un item non esiste (nessun item nella tabella con la chiave primaria specificata), `updateItem` aggiunge un nuovo item alla tabella.
+ Se un item esiste, `updateItem` esegue l'aggiornamento come specificato dal parametro `UpdateExpression`.

**Nota**  
È anche possibile "aggiornare" un item usando `putItem`. Ad esempio, se chiami `putItem` per aggiungere un item alla tabella ma esiste già un item con la chiave primaria specificata, `putItem` sostituisce l'intero item. Se nell'item esistente sono presenti attributi che non sono specificati nell'input, `putItem` rimuove quegli attributi dall'item.  
Come regola generale, ti consigliamo di usare `updateItem` ogni volta che desideri modificare qualsiasi attributo dell'item. Il metodo `updateItem` modifica solo gli attributi specificati nell'input e gli altri attributi dell'item rimangono invariati.

Completare la procedura riportata di seguito. 

1. Crea un'istanza della classe `Table` per rappresentare la tabella da utilizzare.

1. Chiama il metodo `updateTable` dell'istanza di `Table`. Dovrai specificare la chiave primaria dell'item che vuoi recuperare, insieme a una `UpdateExpression` che descrive gli attributi da modificare e come modificarli.

Il seguente esempio di codice Java mostra le attività precedenti. Il codice aggiorna un item libro nella tabella `ProductCatalog`. Aggiunge un nuovo autore al set di `Authors` ed elimina l'attributo `ISBN` esistente. Inoltre, riduce il prezzo di una unità.

Una mappa `ExpressionAttributeValues` viene usata in `UpdateExpression`. I segnaposto `:val1` e `:val2` vengono sostituiti al runtime con i valori effettivi per `Authors` e `Price`.

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

Table table = dynamoDB.getTable("ProductCatalog");

Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#A", "Authors");
expressionAttributeNames.put("#P", "Price");
expressionAttributeNames.put("#I", "ISBN");

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val1",
    new HashSet<String>(Arrays.asList("Author YY","Author ZZ")));
expressionAttributeValues.put(":val2", 1);   //Price

UpdateItemOutcome outcome =  table.updateItem(
    "Id",          // key attribute name
    101,           // key attribute value
    "add #A :val1 set #P = #P - :val2 remove #I", // UpdateExpression
    expressionAttributeNames,
    expressionAttributeValues);
```

### Specifica dei parametri facoltativi
<a name="UpdateItemJavaDocumentAPIOptions"></a>

Insieme ai parametri obbligatori puoi specificare anche dei parametri facoltativi per il metodo `updateItem`, inclusa una condizione che deve essere soddisfatta affinché l'aggiornamento possa avere luogo. Se la condizione specificata non è soddisfatta, AWS SDK per Java genera un`ConditionalCheckFailedException`. Ad esempio, il seguente esempio di codice Java aggiorna in base a condizioni il prezzo di un libro a 25. Specifica una `ConditionExpression` che afferma che il prezzo deve essere aggiornato solo se il prezzo esistente è 20.

**Example**  

```
Table table = dynamoDB.getTable("ProductCatalog");

Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#P", "Price");

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val1", 25);  // update Price to 25...
expressionAttributeValues.put(":val2", 20);  //...but only if existing Price is 20

UpdateItemOutcome outcome = table.updateItem(
    new PrimaryKey("Id",101),
    "set #P = :val1", // UpdateExpression
    "#P = :val2",     // ConditionExpression
    expressionAttributeNames,
    expressionAttributeValues);
```

### Contatore atomico
<a name="AtomicCounterJavaDocumentAPI"></a>

Puoi usare il metodo `updateItem` per implementare un contatore atomico e incrementare o decrementare il valore di un attributo esistente senza interferire con altre richieste di scrittura. Per incrementare un contatore atomico, usa un `UpdateExpression` con un'operazione `set` per aggiungere un valore numerico a un attributo esistente di tipo `Number`.

Il seguente esempio ne dimostra l'uso, incrementando l'attributo `Quantity` di uno. Dimostra anche l'uso del parametro `ExpressionAttributeNames` in una `UpdateExpression`.

```
Table table = dynamoDB.getTable("ProductCatalog");

Map<String,String> expressionAttributeNames = new HashMap<String,String>();
expressionAttributeNames.put("#p", "PageCount");

Map<String,Object> expressionAttributeValues = new HashMap<String,Object>();
expressionAttributeValues.put(":val", 1);

UpdateItemOutcome outcome = table.updateItem(
    "Id", 121,
    "set #p = #p + :val",
    expressionAttributeNames,
    expressionAttributeValues);
```

## Eliminazione di un elemento
<a name="DeleteMidLevelJava"></a>

Il metodo `deleteItem` elimina un item da una tabella. È necessario fornire la chiave primaria dell'item che intendi eliminare.

Completare la procedura riportata di seguito. 

1. Crea un'istanza del client `DynamoDB`.

1. Chiama il metodo `deleteItem` fornendo la chiave dell'item che desideri eliminare. 

Il seguente esempio Java mostra queste attività.

**Example**  

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

Table table = dynamoDB.getTable("ProductCatalog");

DeleteItemOutcome outcome = table.deleteItem("Id", 101);
```

### Specifica dei parametri facoltativi
<a name="DeleteItemJavaDocumentAPIOptions"></a>

Puoi specificare i parametri facoltativi per `deleteItem`. Ad esempio, il seguente esempio di codice Java specifica una `ConditionExpression`, in cui si afferma che un item libro in `InPublication` può essere eliminato solo se il libro non è più in pubblicazione (l'attributo `ProductCatalog` è false).

**Example**  

```
Map<String,Object> expressionAttributeValues = new HashMap<String,Object>();
expressionAttributeValues.put(":val", false);

DeleteItemOutcome outcome = table.deleteItem("Id",103,
    "InPublication = :val",
    null, // ExpressionAttributeNames - not used in this example
    expressionAttributeValues);
```