Database Reference
In-Depth Information
// Create new transaction from the transaction manager
Transaction tx = txm.newTransaction();
Suppose you need to deposit money from one account to another account, then you need
to make updateItem requests, and if both are successful, only then should we commit
the transaction. This can be done as shown in the following code. The following code de-
ducts 100 units from account number 2001:
// Deduct money from account
// Create Hash Map of item with attributes to be updated.
Map<String, AttributeValueUpdate> updateItemsForDebit = new
HashMap<String, AttributeValueUpdate>();
// Hash key of item to be updated
HashMap<String, AttributeValue> primaryKeyForDebit = new
HashMap<String, AttributeValue>();
primaryKeyForDebit.put("accountNumber", new
AttributeValue().withN("2001"));
// Reduce the balance by 100
updateItemsForDebit.put("balance",
new AttributeValueUpdate().withAction(AttributeAction.ADD)
.withValue(new AttributeValue().withN("-100")));
UpdateItemRequest debitRequest = new UpdateItemRequest()
.withTableName("Bank").withKey(primaryKey)
.withReturnValues(ReturnValue.UPDATED_NEW)
.withAttributeUpdates(updateItems);
// Execute the transaction
tx.updateItem(debitRequest);
Now we need to create a similar request that would add and increase the balance by 100 to
account 2002, as follows:
// Add 100 to the balance to account
// Create Hash Map of item with attributes to be updated.
Map<String, AttributeValueUpdate> updateItemsForCredit =
new HashMap<String, AttributeValueUpdate>();
Search WWH ::




Custom Search