다음 코드 예제는 Amazon DynamoDB 항목에 대한 CRUD 작업을 보여줍니다. 이 예에서는 항목을 만들고, 검색하고, 다양한 업데이트를 수행하고, 마지막으로 항목을 삭제합니다.
참고
또한 SDK for Java에서는 객체 지속성 모델을 제공하므로 DynamoDB 테이블로 클라이언트 측 클래스를 매핑할 수 있습니다. 이러한 접근 방식을 활용하면 작성해야 할 코드가 줄어듭니다. 자세한 내용은 Java 1.x: DynamoDBMapper 섹션을 참조하세요.
참고
아래 코드 예제는 DynamoDB에서 테이블 생성 및 코드 예시에 대한 데이터 로드 단원의 지침에 따라 이미 계정의 DynamoDB에 데이터를 로드하였다고 가정한 것입니다.
다음 예제를 실행하기 위한 단계별 지침은 Java 코드 예 섹션을 참조하세요.
package com.amazonaws.codesamples.document;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
public class DocumentAPIItemCRUDExample {
static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
static DynamoDB dynamoDB = new DynamoDB(client);
static String tableName = "ProductCatalog";
public static void main(String[] args) throws IOException {
createItems();
retrieveItem();
// Perform various updates.
updateMultipleAttributes();
updateAddNewAttribute();
updateExistingAttributeConditionally();
// Delete the item.
deleteItem();
}
private static void createItems() {
Table table = dynamoDB.getTable(tableName);
try {
Item item = new Item().withPrimaryKey("Id", 120).withString("Title", "Book 120 Title")
.withString("ISBN", "120-1111111111")
.withStringSet("Authors", new HashSet<String>(Arrays.asList("Author12", "Author22")))
.withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500)
.withBoolean("InPublication", false).withString("ProductCategory", "Book");
table.putItem(item);
item = new Item().withPrimaryKey("Id", 121).withString("Title", "Book 121 Title")
.withString("ISBN", "121-1111111111")
.withStringSet("Authors", new HashSet<String>(Arrays.asList("Author21", "Author 22")))
.withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500)
.withBoolean("InPublication", true).withString("ProductCategory", "Book");
table.putItem(item);
} catch (Exception e) {
System.err.println("Create items failed.");
System.err.println(e.getMessage());
}
}
private static void retrieveItem() {
Table table = dynamoDB.getTable(tableName);
try {
Item item = table.getItem("Id", 120, "Id, ISBN, Title, Authors", null);
System.out.println("Printing item after retrieving it....");
System.out.println(item.toJSONPretty());
} catch (Exception e) {
System.err.println("GetItem failed.");
System.err.println(e.getMessage());
}
}
private static void updateAddNewAttribute() {
Table table = dynamoDB.getTable(tableName);
try {
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 121)
.withUpdateExpression("set #na = :val1").withNameMap(new NameMap().with("#na", "NewAttribute"))
.withValueMap(new ValueMap().withString(":val1", "Some value"))
.withReturnValues(ReturnValue.ALL_NEW);
UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
// Check the response.
System.out.println("Printing item after adding new attribute...");
System.out.println(outcome.getItem().toJSONPretty());
} catch (Exception e) {
System.err.println("Failed to add new attribute in " + tableName);
System.err.println(e.getMessage());
}
}
private static void updateMultipleAttributes() {
Table table = dynamoDB.getTable(tableName);
try {
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 120)
.withUpdateExpression("add #a :val1 set #na=:val2")
.withNameMap(new NameMap().with("#a", "Authors").with("#na", "NewAttribute"))
.withValueMap(
new ValueMap().withStringSet(":val1", "Author YY", "Author ZZ").withString(":val2",
"someValue"))
.withReturnValues(ReturnValue.ALL_NEW);
UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
// Check the response.
System.out.println("Printing item after multiple attribute update...");
System.out.println(outcome.getItem().toJSONPretty());
} catch (Exception e) {
System.err.println("Failed to update multiple attributes in " + tableName);
System.err.println(e.getMessage());
}
}
private static void updateExistingAttributeConditionally() {
Table table = dynamoDB.getTable(tableName);
try {
// Specify the desired price (25.00) and also the condition (price =
// 20.00)
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 120)
.withReturnValues(ReturnValue.ALL_NEW).withUpdateExpression("set #p = :val1")
.withConditionExpression("#p = :val2").withNameMap(new NameMap().with("#p", "Price"))
.withValueMap(new ValueMap().withNumber(":val1", 25).withNumber(":val2", 20));
UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
// Check the response.
System.out.println("Printing item after conditional update to new attribute...");
System.out.println(outcome.getItem().toJSONPretty());
} catch (Exception e) {
System.err.println("Error updating item in " + tableName);
System.err.println(e.getMessage());
}
}
private static void deleteItem() {
Table table = dynamoDB.getTable(tableName);
try {
DeleteItemSpec deleteItemSpec = new DeleteItemSpec().withPrimaryKey("Id", 120)
.withConditionExpression("#ip = :val").withNameMap(new NameMap().with("#ip", "InPublication"))
.withValueMap(new ValueMap().withBoolean(":val", false)).withReturnValues(ReturnValue.ALL_OLD);
DeleteItemOutcome outcome = table.deleteItem(deleteItemSpec);
// Check the response.
System.out.println("Printing item that was deleted...");
System.out.println(outcome.getItem().toJSONPretty());
} catch (Exception e) {
System.err.println("Error deleting item in " + tableName);
System.err.println(e.getMessage());
}
}
}