Last active
December 2, 2020 19:22
-
-
Save espozbob/12df181f22a6f61e7fbac806b9589ae9 to your computer and use it in GitHub Desktop.
AWS - Amazon DynamoDB Transaction Example for Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.vogella.maven.quickstart; | |
import java.util.Arrays; | |
import java.util.Collection; | |
import java.util.HashMap; | |
import java.util.Iterator; | |
import java.util.Map; | |
import com.amazonaws.auth.profile.ProfileCredentialsProvider; | |
import com.amazonaws.regions.Regions; | |
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; | |
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; | |
import com.amazonaws.services.dynamodbv2.document.DynamoDB; | |
import com.amazonaws.services.dynamodbv2.document.Table; | |
import com.amazonaws.services.dynamodbv2.document.TableCollection; | |
import com.amazonaws.services.dynamodbv2.model.AttributeValue; | |
import com.amazonaws.services.dynamodbv2.model.ConditionCheck; | |
import com.amazonaws.services.dynamodbv2.model.InternalServerErrorException; | |
import com.amazonaws.services.dynamodbv2.model.ListTablesResult; | |
import com.amazonaws.services.dynamodbv2.model.Put; | |
import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException; | |
import com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity; | |
import com.amazonaws.services.dynamodbv2.model.ReturnValuesOnConditionCheckFailure; | |
import com.amazonaws.services.dynamodbv2.model.TransactWriteItem; | |
import com.amazonaws.services.dynamodbv2.model.TransactWriteItemsRequest; | |
import com.amazonaws.services.dynamodbv2.model.TransactionCanceledException; | |
import com.amazonaws.services.dynamodbv2.model.Update; | |
import com.google.gson.Gson; | |
/** | |
* AWS DynamoDB Transaction Example for Java | |
* | |
*/ | |
public class App | |
{ | |
public static void main( String[] args ) | |
{ | |
Gson gson = new Gson(); | |
System.out.println(gson.toJson("Amazon DynamoDB Transaction Sample!") ); | |
//Using local profile(default) | |
//AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); | |
//Using custom profile | |
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() | |
.withRegion(Regions.US_EAST_1) | |
.withCredentials(new ProfileCredentialsProvider("profile_test")) | |
.build(); | |
DynamoDB dynamoDB = new DynamoDB(client); | |
//Check your tables in DDB | |
TableCollection<ListTablesResult> tables = dynamoDB.listTables(); | |
Iterator<Table> iterator = tables.iterator(); | |
while (iterator.hasNext()) { | |
Table table = iterator.next(); | |
System.out.println(table.getTableName()); | |
} | |
//Create condition for "Customers" table | |
final String CUSTOMER_TABLE_NAME = "Customers"; | |
final String CUSTOMER_PARTITION_KEY = "CustomerId"; | |
final String customerId = "09e8e9c8-ec48"; //Sample ID that is must created before running | |
final HashMap<String, AttributeValue> customerItemKey = new HashMap<String, AttributeValue>(); | |
customerItemKey.put(CUSTOMER_PARTITION_KEY, new AttributeValue(customerId)); | |
ConditionCheck checkItem = new ConditionCheck() | |
.withTableName(CUSTOMER_TABLE_NAME) | |
.withKey(customerItemKey) | |
.withConditionExpression("attribute_exists(" + CUSTOMER_PARTITION_KEY + ")"); | |
System.out.println(gson.toJson(checkItem) ); | |
//Create condition for "ProductCatalog" table | |
final String PRODUCT_TABLE_NAME = "ProductCatalog"; | |
final String PRODUCT_PARTITION_KEY = "ProductId"; | |
final String productKey = "aaa-001"; //Product ID that is must inserted in the table before running | |
HashMap<String, AttributeValue> productItemKey = new HashMap<String, AttributeValue>(); | |
productItemKey.put(PRODUCT_PARTITION_KEY, new AttributeValue(productKey)); | |
Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>(); | |
expressionAttributeValues.put(":new_status", new AttributeValue("SOLD")); | |
expressionAttributeValues.put(":expected_status", new AttributeValue("IN_STOCK")); | |
Update markItemSold = new Update() | |
.withTableName(PRODUCT_TABLE_NAME) | |
.withKey(productItemKey) | |
.withUpdateExpression("SET ProductStatus = :new_status") //Status ID that is must inserted in the table before running, and have to set "IN_STOCK" | |
.withExpressionAttributeValues(expressionAttributeValues) | |
.withConditionExpression("ProductStatus = :expected_status") | |
.withReturnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD); | |
System.out.println(gson.toJson(markItemSold) ); | |
//Create condition for "Orders" table | |
final String ORDER_PARTITION_KEY = "OrderId"; | |
final String ORDER_TABLE_NAME = "Orders"; | |
final String orderId = "ord-001"; | |
HashMap<String, AttributeValue> orderItem = new HashMap<String, AttributeValue>(); | |
orderItem.put(ORDER_PARTITION_KEY, new AttributeValue(orderId)); | |
orderItem.put(PRODUCT_PARTITION_KEY, new AttributeValue(productKey)); | |
orderItem.put(CUSTOMER_PARTITION_KEY, new AttributeValue(customerId)); | |
orderItem.put("OrderStatus", new AttributeValue("CONFIRMED")); | |
orderItem.put("OrderTotal", new AttributeValue("100")); | |
Put createOrder = new Put() | |
.withTableName(ORDER_TABLE_NAME) | |
.withItem(orderItem) | |
.withReturnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD) | |
.withConditionExpression("attribute_not_exists(" + ORDER_PARTITION_KEY + ")"); | |
System.out.println(gson.toJson(createOrder) ); | |
//Create a transaction with conditions | |
Collection<TransactWriteItem> actions = Arrays.asList( | |
new TransactWriteItem().withConditionCheck(checkItem), | |
new TransactWriteItem().withPut(createOrder), | |
new TransactWriteItem().withUpdate(markItemSold)); | |
TransactWriteItemsRequest placeOrderTransaction = new TransactWriteItemsRequest() | |
.withTransactItems(actions) | |
.withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL); | |
// Execute the transaction and process the result. | |
try { | |
client.transactWriteItems(placeOrderTransaction); | |
System.out.println("Transaction Successful"); | |
} catch (ResourceNotFoundException rnf) { | |
System.err.println("One of the table involved in the transaction is not found" + rnf.getMessage()); | |
} catch (InternalServerErrorException ise) { | |
System.err.println("Internal Server Error" + ise.getMessage()); | |
} catch (TransactionCanceledException tce) { | |
System.out.println("Transaction Canceled " + tce.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Code: https://docs.aws.amazon.com/ko_kr/amazondynamodb/latest/developerguide/transaction-example.html
pom.xml