LoginSignup
2
1

More than 3 years have passed since last update.

【備忘】Amazon DynamoDBへのアクセスプログラム

Last updated at Posted at 2020-07-30

Amazon DynamoDBにアクセスするための基本的なプログラムを記載

1.Entityの用意

@DynamoDBTable(tableName = "テーブル名")
public class SampleTableEntity {
    // HashKey
    @DynamoDBHashKey
    private String hashKey;

    // RangeKey
    @DynamoDBRangeKey
    private String rangeKey;

    // 項目
    @DynamoDBAttribute
    private String item;
}

2.接続

// 指定リージョンのDynamoDBにアクセスするためのClient生成
AmazonDynamoDB amazonDynamoDB = AmazonDynamoDBClientBuilder.standard()
                .withRegion(リージョン名)
                .build();

// テーブルへのMapperを生成
DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDB);

3.データの取り出し(load)

String hashKey="000001";
String rangeKey="000002";
SampleTableEntity entity = mapper.load(SampleTableEntity.class, hashKey, rangekey);

4.データの検索(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);

5.データの検索(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);

6.データの登録・更新(save)

SampleTableEntity entity = new SampleTableEntity();
entity.setHashKey="0000001";
entity.setRangeKey="0000002";
entity.setItem="Item";

mapper.save(entity);
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1