

O AWS SDK para Java 1.x chegou end-of-support em 31 de dezembro de 2025. Recomendamos que você migre para o [AWS SDK for Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/home.html) para continuar recebendo novos recursos, melhorias de disponibilidade e atualizações de segurança.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Trabalho com itens no DynamoDB
<a name="examples-dynamodb-items"></a>

No DynamoDB, um item é um conjunto de *atributos*, e cada um tem um *nome* e um *valor*. Um valor de atributo pode ser uma escalar, um conjunto ou um tipo de documento. Para obter mais informações, consulte [Regras de nomenclatura e tipos de dados](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html) no Guia do desenvolvedor do Amazon DynamoDB.

## Recuperar (obter) um item de uma tabela
<a name="dynamodb-get-item"></a>

Chame o método `getItem` do AmazonDynamoDB e passe um objeto [GetItemRequest](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/GetItemRequest.html) para ele com o nome da tabela e o valor da chave primária do item desejado. Ele retorna um objeto [GetItemResult](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/GetItemResult.html).

Você pode usar o método `getItem()` do objeto `GetItemResult` retornado para recuperar um [Mapa](https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Map.html) dos pares de chave (String) e valor ([AttributeValue](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/AttributeValue.html)) associados ao item.

 **Importações** 

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

 **Código da** 

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

Veja o [exemplo completo](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/GetItem.java) no GitHub.

## Adicionar um novo item a uma tabela
<a name="dynamodb-add-item"></a>

Crie um [Mapa](https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Map.html) de pares de chave/valor que representem os atributos do item. Eles devem incluir valores para os campos de chave primária da tabela. Se o item identificado pela chave primária já existir, os campos serão *atualizados* pela requisição.

**nota**  
Se a tabela nomeada não existir para a conta e a região, um [ResourceNotFoundException](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/ResourceNotFoundException.html) será lançado.

 **Importações** 

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

 **Código da** 

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

Veja o [exemplo completo](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/PutItem.java) no GitHub.

## Atualizar um item existente em uma tabela
<a name="dynamodb-update-item"></a>

Você pode atualizar um atributo para um item já existente em uma tabela usando o método `updateItem` do AmazonDynamoDB, fornecendo um nome de tabela, o valor da chave primária e um mapa de campos a ser atualizado.

**nota**  
Se a tabela nomeada não existir para a conta e a região, ou se o item identificado pela chave primária passada não existir, uma [ResourceNotFoundException](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/model/ResourceNotFoundException.html) será lançada.

 **Importações** 

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

 **Código da** 

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

Veja o [exemplo completo](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateItem.java) no GitHub.

## Usar a classe DynamoDBMapper
<a name="use-the-dynamodbmapper-class"></a>

O [AWS SDK para Java](https://aws.amazon.com/sdk-for-java/) fornece uma classe [DynamoDBMapper](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html), permitindo mapear classes no lado do cliente para tabelas do Amazon DynamoDB. Para usar a classe [DynamoDBMapper](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html), defina o relacionamento entre itens em uma tabela do DynamoDB e suas instâncias de objeto correspondentes no código usando anotações (conforme mostrado no exemplo de código a seguir). A classe [DynamoDBMapper](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html) permite acessar tabelas, realizar várias operações de criação, leitura, atualização e exclusão (CRUD) e executar consultas.

**nota**  
A classe [DynamoDBMapper](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html) não permite criar, atualizar ou excluir tabelas.

 **Importações** 

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

 **Código da** 

O exemplo de código Java a seguir demonstra como adicionar conteúdo à tabela *Music (Música)* usando a classe [DynamoDBMapper](https://docs.aws.amazon.com/sdk-for-java/v1/reference/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapper.html). Depois que o conteúdo é adicionado à tabela, observe que um item é carregado usando as teclas *Partition* e *Sort* . Depois disso, o item *Awards (Prêmios)* é atualizado. Para obter informações sobre como criar a tabela *Música*, consulte [Criar uma tabela](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html) no Guia do desenvolvedor do Amazon DynamoDB.

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

Veja o [exemplo completo](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UseDynamoMapping.java) no GitHub.

## Mais informações
<a name="more-info"></a>
+  [Diretrizes para trabalhar com itens](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForItems.html) no Guia do desenvolvedor do Amazon DynamoDB
+  [Trabalho com itens no DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html) no Guia do Desenvolvedor do Amazon DynamoDB