

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 DynamoDB 的程式設計介面
<a name="Programming.SDKs.Interfaces"></a>

每個 [AWS 軟體開發套件](https://aws.amazon.com/tools)提供一或多個程式化介面，以便與 Amazon DynamoDB 搭配使用。這些介面範圍從簡單的低階 DynamoDB 包裝函式到物件導向的持久性層。可用的界面會根據您使用的 AWS SDK 和程式設計語言而有所不同。

![\[可用於 DynamoDB 的不同 AWS SDKs的程式設計界面。\]](http://docs.aws.amazon.com/zh_tw/amazondynamodb/latest/developerguide/images/SDKSupport.SDKInterfaces.png)


下一節會以 適用於 Java 的 AWS SDK 為範例來重點介紹一些可用的介面。(並非全部介面都可用於所有 AWS 軟體開發套件。)

**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 軟體開發套件都提供低階介面。

下列 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 SDKs提供文件界面，可讓您對資料表和索引執行資料平面操作 （建立、讀取、更新、刪除）。使用文件介面時，您不需要指定 [資料類型描述項](Programming.LowLevelAPI.md#Programming.LowLevelAPI.DataTypeDescriptors)。資料類型是由資料本身的語義隱含的。這些 AWS SDKs也提供方法，可輕鬆將 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) 和 [JavaScript SDK](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/) AWS SDKs 中使用。

下列 Java 程式使用 適用於 Java 的 AWS SDK的文件介面。程式會建立代表 `Music` 資料表的 `Table` 物件，然後要求該物件使用 `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 SDKs提供物件持久性界面，您不會在其中直接執行資料平面操作。反之，您要建立代表 Amazon DynamoDB 資料表和索引中項目的物件，並且僅與這些物件互動。這允許您編寫以物件為中心的程式碼，而不是以資料庫為中心的程式碼。

**注意**  
適用於 Java 和 .NET AWS SDKs 中提供物件持久性界面。如需詳細資訊，請參閱適用於 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();
    }
}
```