[Java] [Memorandum] Access program to Amazon DynamoDB

less than 1 minute read

Described the basic program to access Amazon DynamoDB

1.Preparation of Entity

@DynamoDBTable(tableName = "table name")
public class SampleTableEntity {
    // HashKey
    @DynamoDBHashKey
    private String hashKey;

    // RangeKey
    @DynamoDBRangeKey
    private String rangeKey;

    // item
    @DynamoDBAttribute
    private String item;
}
  1. Connection
// Client generation to access DynamoDB in the specified region
AmazonDynamoDB amazonDynamoDB = AmazonDynamoDBClientBuilder.standard()
.withRegion (region name)
.build();

// Generate Mapper for table
DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDB);

  1. Data loading
String hashKey="000001";
String rangeKey="000002";
SampleTableEntity entity = mapper.load(SampleTableEntity.class, hashKey, rangekey);
  1. Data search (query)
String hashKey="000001";
String rangeKey="000003";

Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
eav.put(":v1", new AttributeValue().withS(hashKey));
eav.put(":v2",new AttributeValue().withS(rangeKey));

DynamoDBQueryExpression<SampleTableEntity> queryExpression = new DynamoDBQueryExpression<SampleTableEntity>()
    .withKeyConditionExpression("hashKey = :v1 and rangeKey <> :v2")
    .withExpressionAttributeValues(eav);

List<SampleTableEntity> entityList = mapper.query(SampleTableEntity.class, queryExpression);
  1. Data search (scan)
String item = "Item";

Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
eav.put(":v1", new AttributeValue().withS(item));

DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
    .withFilterExpression("item = :v1")
    .withExpressionAttributeValues(eav);

List<SampleTableEntity> entityList = mapper.scan(SampleTableEntity.class, scanExpression);
  1. Data registration/update (save)
SampleTableEntity entity = new SampleTableEntity();
entity.setHashKey="0000001";
entity.setRangeKey="0000002";
entity.setItem="Item";

mapper.save(entity);