이전 포스팅에서 AWS SDK for Java 설정과 테이블 설계을 완료 하셨다면 이제 실제로 DynamoDB를 Java를 사용하여 다루어 보겠습니다.
테이블 설계가 완료 되었다면 어떤 Entity를 사용할 지 정하셨겠죠?
대부분 PartitionKey 하나만을 사용하는 Entity가 아니라
PartitionKey + SortKey 인 CompositeKey를 사용하실 것으로 생각합니다.
Entity 설정
Case : Single PrimaryKey
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | @DynamoDBTable(tableName = "Overnodes-tb") public class Entity { private String pk; private String attribute1; private String attribute2; @DynamoDBHashKey(attributeName = "PK") @DynamoDBAutoGeneratedKey public String getPk() { return pk; } @DynamoDBAttribute(attributeName = "Attribute1") public String getAttribute1() { return attribute1; } @DynamoDBAttribute(attributeName = "Attribute2") public String getAttribute2() { return attribute2; } // Other Methods... } |
PartitonKey 하나만을 사용하는 Entity의 설정은 간단합니다.
위와 같이 사용하는 Table 이름과 PK를 잘 설정해주고, 추가할 Attribute들을 정의한 후
CrudRepository를 생성하면 DynamoDB에 기본 CRUD 명령을 내릴 수 있습니다.
| @EnableScan public interface EntityRepository extends CrudRepository<Entity, String> { } |
기존 다른 DB들의 Repository 생성방법과 다른 부분은 @EnableScan Annotation을 사용한다는 것입니다.
| @Configuration @EnableDynamoDBRepositories(basePackageClasses = {EntityRepository.class}) public class DynamodbEC2Config { ... } |
basePackageClasses 부분을 생성한 Repository로 지정해주시면 됩니다.
Case : Composite PrimaryKey
CompositeKey를 사용하는 Entity는 아래처럼 설정해주셔야 합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | @DynamoDBTable(tableName = "Overnodes-tb") public class Entity { @Id private EntityKey ; private String attribute1; private String attribute2; @DynamoDBHashKey(attributeName = "PK") public String getPk() { return EntityKey != null ? EntityKey.getPk() : null; } public void setPk(String pk) { if (EntityKey == null) { EntityKey = new EntityKey(); } EntityKey.setPk(pk); } @DynamoDBRangeKey(attributeName = "SK") public String getSk() { return EntityKey != null ? EntityKey.getSk() : null; } public void setSk(String sk) { if (EntityKey == null) { EntityKey = new EntityKey(); } EntityKey.setSk(sk); } @DynamoDBAttribute(attributeName = "Attribute1") public String getAttribute1() { return attribute1; } @DynamoDBAttribute(attributeName = "Attribute2") public String getAttribute2() { return attribute2; } // Other Methods... } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class EntitiyKey implements Serializable { private String pk; private String sk; public EntitiyKey() { } @DynamoDBHashKey(attributeName = "PK") public String getPk() { return pk; } public void setPk(String pk) { this.pk = pk; } @DynamoDBRangeKey(attributeName = "SK") public String getSk() { return sk; } public void setSk(String sk) { this.sk = sk; } // Other Methods... |
그리고 사용할 Entity Class가 그 키를 가지고, 조작하는 메서드를 가지도록 되어있습니다.
이상으로 포스팅을 마칩니다.
다음에 더 좋은 내용으로 만나요~
By RyanKim (Overnodes Devloper)