[Note] Access program for Amazon DynamoDB

Describes the basic program for accessing 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 to table
DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDB);

  1. Load data
String hashKey="000001";
String rangeKey="000002";
SampleTableEntity entity = mapper.load(SampleTableEntity.class, hashKey, rangekey);
  1. Data query (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. Scan data
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);

Recommended Posts

[Note] Access program for Amazon DynamoDB