处理 DynamoDB 中的项目 - Amazon SDK for Java 1.x
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

我们宣布了即将推出 end-of-support 的 Amazon SDK for Java (v1)。建议您迁移到 Amazon SDK for Java v2。有关日期、其他详细信息以及如何迁移的信息,请参阅链接的公告。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

处理 DynamoDB 中的项目

在 DynamoDB 中,项目是属性的集合,每个项目都包括一个名称和一个。属性值可以为标量、集或文档类型。有关更多信息,请参阅《Amazon DynamoDB 开发人员指南》中的命名规则和数据类型

检索 (获取) 表中的项目

调用 AmazonDynamoDB 的 getItem 方法,并向其传递 GetItemRequest 对象,包含您所需项目的表名称和主键值。它返回 GetItemResult 对象。

可以使用所返回 GetItemResult 对象的 getItem() 方法,检索与项目关联的映射(键(字符串) 和值 (AttributeValue) 对)。

导入

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;

代码

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

请参阅 GitHub 上的完整示例

向表添加新项目

创建表示项目属性的键值对的映射。其中必须包括表的主键字段的值。如果主键标识的项目已存在,那么其字段将通过该请求更新

注意

如果您的账户和区域没有该已命名的表,则将引发 ResourceNotFoundException 异常。

导入

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;

代码

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

请参阅 GitHub 上的完整示例

更新表中现有项目

可以使用 AmazonDynamoDB 的 updateItem 方法,通过提供要更新的表名称、主键值和字段映射,更新表中已有项目的属性。

注意

如果您的账户和区域没有该已命名的表,或者不存在传入的主键标识的项目,会导致 ResourceNotFoundException 异常。

导入

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;

代码

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

请参阅 GitHub 上的完整示例

使用 DynamoDBMapper 类

Amazon SDK for Java 提供了 DynamoDBMapper 类,使您能够将客户端类映射到 Amazon DynamoDB 表。要使用 DynamoDBMapper 类,您可以使用注释定义 DynamoDB 表中的项目与代码中相应的对象实例之间的关系(如下面的代码示例所示)。利用 DynamoDBMapper 类,您能够访问自己的表,执行各种创建、读取、更新和删除 (CRUD) 操作,并执行查询。

注意

DynamoDBMapper 类不允许创建、更新或删除表。

导入

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;

代码

以下 Java 代码示例演示如何使用 DynamoDBMapper 类向 Music 表添加内容。将内容添加到表中后,请注意使用 Partition (分区)Sort (排序) 键加载项目。然后 Awards (奖项) 项目会更新。有关创建 Music 表的信息,请参阅《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; } }

请参阅 GitHub 上的完整示例

更多信息