本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
在 DynamoDB 中处理项目
在 DynamoDB 中,项目是属性的集合,每个项目都包括一个名称和一个值。属性值可以为标量、集或文档类型。有关更多信息,请参阅 中的命名规则和数据类型Amazon DynamoDB Developer Guide。
检索 (获取) 表中的项目
调用 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 key_to_get =
new HashMap();
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 returned_item =
ddb.getItem(request).getItem();
if (returned_item != null) {
Set 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。
在表中添加新项目
创建表示项目属性的键值对的映射。其中必须包括表的主键字段的值。如果主键标识的项目已存在,那么其字段将通过该请求更新。
注意
导入
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 item_values =
new HashMap();
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 item_key =
new HashMap();
item_key.put("Name", new AttributeValue(name));
HashMap updated_values =
new HashMap();
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 类
适用于 Java 的 AWS 开发工具包提供了一个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 代码示例向您演示如何使用 类向 MusicDynamoDBMapper 表添加内容。将内容添加到表中后,请注意使用 Partition (分区) 和 Sort (排序) 键加载项目。然后 Awards (奖项) 项目会更新。有关创建 Music 表的信息,请参阅 中的创建表Amazon DynamoDB Developer Guide。
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。
更多信息
中的项目处理准则Amazon DynamoDB Developer Guide
中的DynamoDB在 中使用项目Amazon DynamoDB Developer Guide