

Le AWS SDK pour Java 1.x a été atteint end-of-support le 31 décembre 2025. Nous vous recommandons de migrer vers le pour continuer [AWS SDK for Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/home.html)à bénéficier des nouvelles fonctionnalités, des améliorations de disponibilité et des mises à jour de sécurité.

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# DynamoDB Exemples d'utilisation du AWS SDK pour Java
<a name="examples-dynamodb"></a>

Cette section fournit des exemples de programmation d'[DynamoDB](https://aws.amazon.com/dynamodb/) à l'aide du kit [AWS SDK pour Java](https://aws.amazon.com/sdk-for-java/).

**Note**  
Les exemples incluent uniquement le code nécessaire pour démontrer chaque technique. L'[exemple de code complet est disponible sur GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/java). À partir de là, vous pouvez télécharger un fichier source unique ou cloner le référentiel en local pour obtenir tous les exemples à générer et exécuter.

**Topics**
+ [Utiliser des points de AWS terminaison basés sur des comptes](#account-based-endpoint-routing)
+ [Utilisation de tables dans DynamoDB](examples-dynamodb-tables.md)
+ [Utilisation d'éléments dans DynamoDB](examples-dynamodb-items.md)

## Utiliser des points de AWS terminaison basés sur des comptes
<a name="account-based-endpoint-routing"></a>

DynamoDB [AWS propose des points de terminaison basés sur des comptes](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.SDKOverview.html#Programming.SDKs.endpoints) qui peuvent améliorer les performances en utilisant AWS votre identifiant de compte pour rationaliser le routage des demandes. 

Pour bénéficier de cette fonctionnalité, vous devez utiliser la version 1.12.771 ou supérieure de la version 1 de. AWS SDK pour Java La dernière version du SDK est répertoriée dans le référentiel [central de Maven](https://central.sonatype.com/artifact/com.amazonaws/aws-java-sdk-bom). Une fois qu'une version prise en charge du SDK est active, elle utilise automatiquement les nouveaux points de terminaison.

Si vous souhaitez désactiver le routage basé sur le compte, quatre options s'offrent à vous :
+ Configurez un client de service DynamoDB avec `AccountIdEndpointMode` le paramètre défini sur. `DISABLED`
+ Définissez une variable d'environnement.
+ Définissez une propriété du système JVM.
+ Mettez à jour le paramètre du fichier de AWS configuration partagé.

L'extrait suivant illustre comment désactiver le routage basé sur un compte en configurant un client de service DynamoDB :

```
ClientConfiguration config = new ClientConfiguration()
    .withAccountIdEndpointMode(AccountIdEndpointMode.DISABLED);
AWSCredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

AmazonDynamoDB dynamodb = AmazonDynamoDBClientBuilder.standard()
    .withClientConfiguration(config)
    .withCredentials(credentialsProvider)
    .withRegion(Regions.US_WEST_2)
    .build();
```

Le guide de référence AWS SDKs and Tools fournit plus d'informations sur les [trois dernières options de configuration](https://docs.aws.amazon.com/sdkref/latest/guide/feature-account-endpoints.html).

# Utilisation de tables dans DynamoDB
<a name="examples-dynamodb-tables"></a>

Les tables sont les conteneurs de tous les éléments d'une DynamoDB base de données. Avant de pouvoir ajouter ou supprimer des données DynamoDB, vous devez créer une table.

Pour chaque table, vous devez définir :
+ Un *nom* de table unique pour le compte et la région.
+ Une *clé primaire* pour laquelle chaque valeur doit être unique : deux éléments de votre table ne peuvent pas avoir la même valeur de clé primaire.

  Une clé primaire peut être *simple*, constituée d'une seule clé de partition (HASH) ou *composite*, constituée d'une partition et d'une clé de tri (RANGE).

  Chaque valeur clé est associée à un *type de données*, énuméré par la [ScalarAttributeType](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/ScalarAttributeType.html)classe. La valeur de la clé peut être binaire (B), numérique (N) ou de type chaîne (S). Pour plus d'informations, consultez la section [Règles de dénomination et types de données](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html) dans le Guide du Amazon DynamoDB développeur.
+  Des valeurs de *débit alloué* qui définissent le nombre d'unités de capacité en lecture/écriture réservées pour la table.
**Note**  
Amazon DynamoDB la [tarification](https://aws.amazon.com/dynamodb/pricing/) est basée sur les valeurs de débit provisionnées que vous définissez sur vos tables. Ne réservez donc que la capacité dont vous pensez avoir besoin pour votre table.

Le débit alloué pour une table peut être modifié à tout moment pour que vous puissiez ajuster la capacité si vos besoins évoluent.

## Création d’une table
<a name="dynamodb-create-table"></a>

Utilisez la `createTable` méthode du [DynamoDB client](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/AmazonDynamoDB.html) pour créer une nouvelle DynamoDB table. Vous devez créer des attributs de table et un schéma de table qui sont utilisés pour identifier la clé primaire de votre table. Vous devez également fournir des valeurs initiales de débit alloué et un nom de table. Définissez les attributs clés du tableau uniquement lors de la création de votre DynamoDB tableau.

**Note**  
Si une table portant le nom que vous avez choisi existe déjà, une table [AmazonServiceException](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/AmazonServiceException.html)est émise.

 **Importations** 

```
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.CreateTableResult;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
```

### Création d'une table avec une clé primaire simple
<a name="dynamodb-create-table-simple"></a>

Ce code crée une table avec une clé primaire simple ("Name").

 **Code** 

```
CreateTableRequest request = new CreateTableRequest()
    .withAttributeDefinitions(new AttributeDefinition(
             "Name", ScalarAttributeType.S))
    .withKeySchema(new KeySchemaElement("Name", KeyType.HASH))
    .withProvisionedThroughput(new ProvisionedThroughput(
             new Long(10), new Long(10)))
    .withTableName(table_name);

final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

try {
    CreateTableResult result = ddb.createTable(request);
    System.out.println(result.getTableDescription().getTableName());
} catch (AmazonServiceException e) {
    System.err.println(e.getErrorMessage());
    System.exit(1);
}
```

Voir l'[exemple complet](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/CreateTable.java) sur GitHub.

### Création d'une table avec une clé primaire composite
<a name="dynamodb-create-table-composite"></a>

Ajoutez-en un autre [AttributeDefinition](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/AttributeDefinition.html)et [KeySchemaElement](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/KeySchemaElement.html)à [CreateTableRequest](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/CreateTableRequest.html).

 **Code** 

```
CreateTableRequest request = new CreateTableRequest()
    .withAttributeDefinitions(
          new AttributeDefinition("Language", ScalarAttributeType.S),
          new AttributeDefinition("Greeting", ScalarAttributeType.S))
    .withKeySchema(
          new KeySchemaElement("Language", KeyType.HASH),
          new KeySchemaElement("Greeting", KeyType.RANGE))
    .withProvisionedThroughput(
          new ProvisionedThroughput(new Long(10), new Long(10)))
    .withTableName(table_name);
```

Voir l'[exemple complet](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/CreateTableCompositeKey.java) sur GitHub.

## Affichage d'une liste de tables
<a name="dynamodb-list-tables"></a>

Vous pouvez répertorier les tables d'une région donnée en appelant la `listTables` méthode du [DynamoDB client](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/AmazonDynamoDB.html).

**Note**  
Si la table nommée n'existe pas pour votre compte et votre région, un [ResourceNotFoundException](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/ResourceNotFoundException.html)est généré.

 **Importations** 

```
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.ListTablesRequest;
import com.amazonaws.services.dynamodbv2.model.ListTablesResult;
```

 **Code** 

```
final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

ListTablesRequest request;

boolean more_tables = true;
String last_name = null;

while(more_tables) {
    try {
        if (last_name == null) {
        	request = new ListTablesRequest().withLimit(10);
        }
        else {
        	request = new ListTablesRequest()
        			.withLimit(10)
        			.withExclusiveStartTableName(last_name);
        }

        ListTablesResult table_list = ddb.listTables(request);
        List<String> table_names = table_list.getTableNames();

        if (table_names.size() > 0) {
            for (String cur_name : table_names) {
                System.out.format("* %s\n", cur_name);
            }
        } else {
            System.out.println("No tables found!");
            System.exit(0);
        }

        last_name = table_list.getLastEvaluatedTableName();
        if (last_name == null) {
            more_tables = false;
        }
```

Par défaut, jusqu'à 100 tables sont renvoyées par appel. À utiliser `getLastEvaluatedTableName` sur l'[ListTablesResult](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/model/ListTablesResult.html)objet renvoyé pour obtenir la dernière table évaluée. Vous pouvez utiliser cette valeur pour démarrer la liste après la dernière valeur renvoyée de la liste précédente.

Voir l'[exemple complet](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/ListTables.java) sur GitHub.

## Description d'une table (obtention d'informations sur celle-ci)
<a name="dynamodb-describe-table"></a>

Appelez la `describeTable` méthode du [DynamoDB client](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/AmazonDynamoDB.html).

**Note**  
Si la table nommée n'existe pas pour votre compte et votre région, un [ResourceNotFoundException](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/ResourceNotFoundException.html)est généré.

 **Importations** 

```
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughputDescription;
import com.amazonaws.services.dynamodbv2.model.TableDescription;
```

 **Code** 

```
final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

try {
    TableDescription table_info =
       ddb.describeTable(table_name).getTable();

    if (table_info != null) {
        System.out.format("Table name  : %s\n",
              table_info.getTableName());
        System.out.format("Table ARN   : %s\n",
              table_info.getTableArn());
        System.out.format("Status      : %s\n",
              table_info.getTableStatus());
        System.out.format("Item count  : %d\n",
              table_info.getItemCount().longValue());
        System.out.format("Size (bytes): %d\n",
              table_info.getTableSizeBytes().longValue());

        ProvisionedThroughputDescription throughput_info =
           table_info.getProvisionedThroughput();
        System.out.println("Throughput");
        System.out.format("  Read Capacity : %d\n",
              throughput_info.getReadCapacityUnits().longValue());
        System.out.format("  Write Capacity: %d\n",
              throughput_info.getWriteCapacityUnits().longValue());

        List<AttributeDefinition> attributes =
           table_info.getAttributeDefinitions();
        System.out.println("Attributes");
        for (AttributeDefinition a : attributes) {
            System.out.format("  %s (%s)\n",
                  a.getAttributeName(), a.getAttributeType());
        }
    }
} catch (AmazonServiceException e) {
    System.err.println(e.getErrorMessage());
    System.exit(1);
}
```

Voir l'[exemple complet](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DescribeTable.java) sur GitHub.

## Modification (mise à jour) d'une table
<a name="dynamodb-update-table"></a>

Vous pouvez modifier les valeurs de débit provisionnées de votre table à tout moment en appelant la méthode du [DynamoDB`updateTable`client](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/AmazonDynamoDB.html).

**Note**  
Si la table nommée n'existe pas pour votre compte et votre région, un [ResourceNotFoundException](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/ResourceNotFoundException.html)est généré.

 **Importations** 

```
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.AmazonServiceException;
```

 **Code** 

```
ProvisionedThroughput table_throughput = new ProvisionedThroughput(
      read_capacity, write_capacity);

final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

try {
    ddb.updateTable(table_name, table_throughput);
} catch (AmazonServiceException e) {
    System.err.println(e.getErrorMessage());
    System.exit(1);
}
```

Voir l'[exemple complet](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateTable.java) sur GitHub.

## Suppression d'une table
<a name="dynamodb-delete-table"></a>

Appelez la `deleteTable` méthode du [DynamoDB client](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/AmazonDynamoDB.html) et transmettez-lui le nom de la table.

**Note**  
Si la table nommée n'existe pas pour votre compte et votre région, un [ResourceNotFoundException](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/ResourceNotFoundException.html)est généré.

 **Importations** 

```
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
```

 **Code** 

```
final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

try {
    ddb.deleteTable(table_name);
} catch (AmazonServiceException e) {
    System.err.println(e.getErrorMessage());
    System.exit(1);
}
```

Voir l'[exemple complet](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DeleteTable.java) sur GitHub.

## Plus d'informations
<a name="more-info"></a>
+  [Instructions relatives à l'utilisation des tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html) dans le guide du Amazon DynamoDB développeur
+  [Utilisation des tableaux DynamoDB dans](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html) le guide du Amazon DynamoDB développeur

# Utilisation d'éléments dans DynamoDB
<a name="examples-dynamodb-items"></a>

Dans DynamoDB, un élément est un ensemble d'*attributs*, chacun ayant un *nom* et une *valeur*. Une valeur d'attribut peut être de type scalar, set ou document. Pour plus d'informations, consultez la section [Règles de dénomination et types de données](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html) dans le Guide du Amazon DynamoDB développeur.

## Extraction (Get) d'un élément d'une table
<a name="dynamodb-get-item"></a>

Appelez la `getItem` méthode AmazonDynamo de la base de données et transmettez-lui un [GetItemRequest](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/GetItemRequest.html)objet avec le nom de la table et la valeur de la clé primaire de l'élément souhaité. Elle renvoie un [GetItemResult](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/GetItemResult.html)objet.

Vous pouvez utiliser la `getItem()` méthode de l'`GetItemResult`objet renvoyé pour récupérer une [carte](https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Map.html) des paires clé (chaîne [AttributeValue](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/AttributeValue.html)) et valeur () associées à l'élément.

 **Importations** 

```
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.GetItemRequest;
import java.util.HashMap;
import java.util.Map;
```

 **Code** 

```
HashMap<String,AttributeValue> key_to_get =
    new HashMap<String,AttributeValue>();

key_to_get.put("DATABASE_NAME", new AttributeValue(name));

GetItemRequest request = null;
if (projection_expression != null) {
    request = new GetItemRequest()
        .withKey(key_to_get)
        .withTableName(table_name)
        .withProjectionExpression(projection_expression);
} else {
    request = new GetItemRequest()
        .withKey(key_to_get)
        .withTableName(table_name);
}

final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

try {
    Map<String,AttributeValue> returned_item =
       ddb.getItem(request).getItem();
    if (returned_item != null) {
        Set<String> keys = returned_item.keySet();
        for (String key : keys) {
            System.out.format("%s: %s\n",
                    key, returned_item.get(key).toString());
        }
    } else {
        System.out.format("No item found with the key %s!\n", name);
    }
} catch (AmazonServiceException e) {
    System.err.println(e.getErrorMessage());
    System.exit(1);
```

Consultez l'[exemple complet](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/GetItem.java) sur GitHub.

## Ajout d'un nouvel élément à une table
<a name="dynamodb-add-item"></a>

Créez un [mappage](https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Map.html) des paires clé-valeur qui représentent les attributs de l'élément. Elles doivent inclure les valeurs des champs de clé primaire de la table. Si l'élément identifié par la clé primaire existe déjà, ses champs sont *mis à jour* par la demande.

**Note**  
Si la table nommée n'existe pas pour votre compte et votre région, un [ResourceNotFoundException](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/ResourceNotFoundException.html)est généré.

 **Importations** 

```
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException;
import java.util.ArrayList;
```

 **Code** 

```
HashMap<String,AttributeValue> item_values =
    new HashMap<String,AttributeValue>();

item_values.put("Name", new AttributeValue(name));

for (String[] field : extra_fields) {
    item_values.put(field[0], new AttributeValue(field[1]));
}

final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

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

Consultez l'[exemple complet](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/PutItem.java) sur GitHub.

## Mise à jour d'un élément existant dans une table
<a name="dynamodb-update-item"></a>

Vous pouvez mettre à jour un attribut pour un élément qui existe déjà dans une table en utilisant la `updateItem` méthode de la AmazonDynamo base de données, en fournissant un nom de table, une valeur de clé primaire et une carte des champs à mettre à jour.

**Note**  
Si la table nommée n'existe pas pour votre compte et votre région, ou si l'élément identifié par la clé primaire que vous avez transmise n'existe pas, un [ResourceNotFoundException](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/ResourceNotFoundException.html)est généré.

 **Importations** 

```
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeAction;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate;
import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException;
import java.util.ArrayList;
```

 **Code** 

```
HashMap<String,AttributeValue> item_key =
   new HashMap<String,AttributeValue>();

item_key.put("Name", new AttributeValue(name));

HashMap<String,AttributeValueUpdate> updated_values =
    new HashMap<String,AttributeValueUpdate>();

for (String[] field : extra_fields) {
    updated_values.put(field[0], new AttributeValueUpdate(
                new AttributeValue(field[1]), AttributeAction.PUT));
}

final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

try {
    ddb.updateItem(table_name, item_key, updated_values);
} catch (ResourceNotFoundException e) {
    System.err.println(e.getMessage());
    System.exit(1);
} catch (AmazonServiceException e) {
    System.err.println(e.getMessage());
    System.exit(1);
```

Consultez l'[exemple complet](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateItem.java) sur GitHub.

## Utiliser la classe Dynamo DBMapper
<a name="use-the-dynamodbmapper-class"></a>

[AWS SDK pour Java](https://aws.amazon.com/sdk-for-java/)fournit une DBMapper classe [Dynamo](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html), qui vous permet de mapper vos classes côté client à des tables. Amazon DynamoDB Pour utiliser la DBMapper classe [Dynamo](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html), vous définissez la relation entre les éléments d'une DynamoDB table et leurs instances d'objet correspondantes dans votre code à l'aide d'annotations (comme indiqué dans l'exemple de code suivant). La DBMapper classe [Dynamo](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html) vous permet d'accéder à vos tables, d'effectuer diverses opérations de création, de lecture, de mise à jour et de suppression (CRUD) et d'exécuter des requêtes.

**Note**  
La DBMapper classe [Dynamo](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html) ne vous permet pas de créer, de mettre à jour ou de supprimer des tables.

 **Importations** 

```
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey;
import com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException;
```

 **Code** 

L'exemple de code Java suivant montre comment ajouter du contenu à la table *Music* à l'aide de la DBMapper classe [Dynamo](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html). Une fois le contenu ajouté à la table, notez qu'un élément est chargé à l'aide des clés de *partition* et de *tri*. Ensuite, l'élément *Awards* est mis à jour. Pour plus d'informations sur la création de la table *musicale*, voir [Création d'une table](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html) dans le guide du Amazon DynamoDB développeur.

```
       AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
       MusicItems items = new MusicItems();

       try{
           // Add new content to the Music table
           items.setArtist(artist);
           items.setSongTitle(songTitle);
           items.setAlbumTitle(albumTitle);
           items.setAwards(Integer.parseInt(awards)); //convert to an int

           // Save the item
           DynamoDBMapper mapper = new DynamoDBMapper(client);
           mapper.save(items);

           // Load an item based on the Partition Key and Sort Key
           // Both values need to be passed to the mapper.load method
           String artistName = artist;
           String songQueryTitle = songTitle;

           // Retrieve the item
           MusicItems itemRetrieved = mapper.load(MusicItems.class, artistName, songQueryTitle);
           System.out.println("Item retrieved:");
           System.out.println(itemRetrieved);

           // Modify the Award value
           itemRetrieved.setAwards(2);
           mapper.save(itemRetrieved);
           System.out.println("Item updated:");
           System.out.println(itemRetrieved);

           System.out.print("Done");
       } catch (AmazonDynamoDBException e) {
           e.getStackTrace();
       }
   }

   @DynamoDBTable(tableName="Music")
   public static class MusicItems {

       //Set up Data Members that correspond to columns in the Music table
       private String artist;
       private String songTitle;
       private String albumTitle;
       private int awards;

       @DynamoDBHashKey(attributeName="Artist")
       public String getArtist() {
           return this.artist;
       }

       public void setArtist(String artist) {
           this.artist = artist;
       }

       @DynamoDBRangeKey(attributeName="SongTitle")
       public String getSongTitle() {
           return this.songTitle;
       }

       public void setSongTitle(String title) {
           this.songTitle = title;
       }

       @DynamoDBAttribute(attributeName="AlbumTitle")
       public String getAlbumTitle() {
           return this.albumTitle;
       }

       public void setAlbumTitle(String title) {
           this.albumTitle = title;
       }

       @DynamoDBAttribute(attributeName="Awards")
       public int getAwards() {
           return this.awards;
       }

       public void setAwards(int awards) {
           this.awards = awards;
       }
   }
```

Consultez l'[exemple complet](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UseDynamoMapping.java) sur GitHub.

## Plus d'informations
<a name="more-info"></a>
+  [Directives relatives à l'utilisation des éléments](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForItems.html) du guide du Amazon DynamoDB développeur
+  [Utilisation des éléments contenus DynamoDB dans](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html) le guide du Amazon DynamoDB développeur