

# 与 DynamoDB 配合使用的编程接口
<a name="Programming.SDKs.Interfaces"></a>

每个 [AWS SDK](https://aws.amazon.com/tools) 提供了一个或多个用于使用 Amazon DynamoDB 的编程接口。这些接口范围从简单的低级 DynamoDB 包装到面向对象的持久层。可用接口因您使用的 AWS SDK 和编程语言而不同。

![\[不同 AWS SDK 中提供了用于 DynamoDB 的编程接口。\]](http://docs.aws.amazon.com/zh_cn/amazondynamodb/latest/developerguide/images/SDKSupport.SDKInterfaces.png)


以下部分重点介绍了一些可用的接口，使用适用于 Java 的 AWS SDK作为一个示例。（并非所有接口都可用于所有 AWS SDK。）

**Topics**
+ [与 DynamoDB 配合使用的低级别接口](#Programming.SDKs.Interfaces.LowLevel)
+ [与 DynamoDB 配合使用的文档接口](#Programming.SDKs.Interfaces.Document)
+ [与 DynamoDB 配合使用的对象持久化接口](#Programming.SDKs.Interfaces.Mapper)

## 与 DynamoDB 配合使用的低级别接口
<a name="Programming.SDKs.Interfaces.LowLevel"></a>

每个语言特定 AWS SDK 为 Amazon DynamoDB 提供了一个低级别接口，其方法与低级别 DynamoDB API 请求非常相似。

在某些情况下，您需要使用 [数据类型描述符](Programming.LowLevelAPI.md#Programming.LowLevelAPI.DataTypeDescriptors) 识别数据类型，例如 `S` 对于字符串，`N` 对于数字。

**注意**  
一个低级别接口可用于每种特定语言 AWS SDK。

下面的 Java 程序使用低级别 适用于 Java 的 AWS SDK 接口。

### 低级别接口示例
<a name="low-level-example"></a>

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 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 get an item from an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client, see the EnhancedGetItem example.
 */
public class GetItem {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <key> <keyVal>

                Where:
                    tableName - The Amazon DynamoDB table from which an item is retrieved (for example, Music3).\s
                    key - The key used in the Amazon DynamoDB table (for example, Artist).\s
                    keyval - The key value that represents the item to get (for example, Famous Band).
                """;

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

        String tableName = args[0];
        String key = args[1];
        String keyVal = args[2];
        System.out.format("Retrieving item \"%s\" from \"%s\"\n", keyVal, tableName);
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        getDynamoDBItem(ddb, tableName, key, keyVal);
        ddb.close();
    }

    public static void getDynamoDBItem(DynamoDbClient ddb, String tableName, String key, String keyVal) {
        HashMap<String, AttributeValue> keyToGet = new HashMap<>();
        keyToGet.put(key, AttributeValue.builder()
                .s(keyVal)
                .build());

        GetItemRequest request = GetItemRequest.builder()
                .key(keyToGet)
                .tableName(tableName)
                .build();

        try {
            // If there is no matching item, GetItem does not return any data.
            Map<String, AttributeValue> returnedItem = ddb.getItem(request).item();
            if (returnedItem.isEmpty())
                System.out.format("No item found with the key %s!\n", key);
            else {
                Set<String> keys = returnedItem.keySet();
                System.out.println("Amazon DynamoDB table attributes: \n");
                for (String key1 : keys) {
                    System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString());
                }
            }

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```

## 与 DynamoDB 配合使用的文档接口
<a name="Programming.SDKs.Interfaces.Document"></a>

许多 AWS SDK 提供文档接口，允许您对表和索引执行数据层面操作（创建、读取、更新、删除）。对于文档接口，无需指定 [数据类型描述符](Programming.LowLevelAPI.md#Programming.LowLevelAPI.DataTypeDescriptors)。数据类型由数据本身的语义隐含。这些 AWS SDK 还提供了一些方法，可以在 JSON 文档转换为 Amazon DynamoDB 本机数据类型之间轻松转换。

**注意**  
适用于 [Java](https://aws.amazon.com/sdk-for-java)、[.NET](https://aws.amazon.com/sdk-for-net)、[Node.js](https://aws.amazon.com/sdk-for-node-js) 的 AWS SDK 和 [JavaScript SDK](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/) 中可用的文档接口。

以下 Java 程序使用 适用于 Java 的 AWS SDK 的文档接口。程序创建一个 `Table` 对象，表示 `Music` 表，然后要求该对象使用 `GetItem` 检索歌曲。然后程序打印该歌曲的发行年份。

`software.amazon.dynamodb.document.DynamoDB` 类实施 DynamoDB 文档接口。注意`DynamoDB`充当一个围绕低级别客户端的包装程序 (`AmazonDynamoDB`)。

### 文档接口示例
<a name="document-level-example"></a>

```
package com.amazonaws.codesamples.gsg;

import software.amazon.dynamodb.AmazonDynamoDB;
import software.amazon.dynamodb.AmazonDynamoDBClientBuilder;
import software.amazon.dynamodb.document.DynamoDB;
import software.amazon.dynamodb.document.GetItemOutcome;
import software.amazon.dynamodb.document.Table;

public class MusicDocumentDemo {

    public static void main(String[] args) {

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

        Table table = docClient.getTable("Music");
        GetItemOutcome outcome = table.getItemOutcome(
                "Artist", "No One You Know",
                "SongTitle", "Call Me Today");

        int year = outcome.getItem().getInt("Year");
        System.out.println("The song was released in " + year);

    }
}
```

## 与 DynamoDB 配合使用的对象持久化接口
<a name="Programming.SDKs.Interfaces.Mapper"></a>

如果不直接执行数据层面操作，一些 AWS SDK 提供对象持久化接口。相反，您可以创建表示 Amazon DynamoDB 表和索引中项目的对象，并且仅与这些对象进行交互。这允许您编写以对象为中心的代码，而不是以数据库为中心的代码。

**注意**  
适用于 Java 和 .NET 的 AWS SDK 提供对象持久化接口。有关更多信息，请参阅 DynamoDB 的[用于 DynamoDB 的更高级别编程接口](HigherLevelInterfaces.md)。

### 对象持久化接口示例
<a name="mapper-level-example"></a>

```
import com.example.dynamodb.Customer;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
```

```
import com.example.dynamodb.Customer;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;

/*
 * Before running this code example, create an Amazon DynamoDB table named Customer with these columns:
 *   - id - the id of the record that is the key. Be sure one of the id values is `id101`
 *   - custName - the customer name
 *   - email - the email value
 *   - registrationDate - an instant value when the item was added to the table. These values
 *                        need to be in the form of `YYYY-MM-DDTHH:mm:ssZ`, such as 2022-07-11T00:00:00Z
 *
 * Also, ensure that you have set up your development environment, including your credentials.
 *
 * For information, see this documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class EnhancedGetItem {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(ddb)
                .build();

        getItem(enhancedClient);
        ddb.close();
    }

    public static String getItem(DynamoDbEnhancedClient enhancedClient) {
        Customer result = null;
        try {
            DynamoDbTable<Customer> table = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class));
            Key key = Key.builder()
                    .partitionValue("id101").sortValue("tred@noserver.com")
                    .build();

            // Get the item by using the key.
            result = table.getItem(
                    (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key));
            System.out.println("******* The description value is " + result.getCustName());

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return result.getCustName();
    }
}
```