본문 바로가기

프로젝트 & TIL/일별 공부 기록 (백엔드 스쿨)

96일차 - 다이나모DB 저장과 조회

devtools 의존성 제거

- 다이나모DB 라이브러리와 호환되지 않는다.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
//    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

    implementation 'software.amazon.awssdk:dynamodb:2.20.98'
    implementation 'software.amazon.awssdk:dynamodb-enhanced:2.20.98'
}

 


데이터 저장하기

DynamoDbConfig

@Configuration(enforceUniqueMethods = false)
public class DynamoDbConfig {

    @Value("${aws.accessKeyId}")
    private String awsAccessKey;

    @Value("${aws.secretKey}")
    private String awsSecretKey;

    @Value("${aws.region}")
    private String awsRegion;

    @Bean
    public DynamoDbClient dynamoDbClient() {
        return DynamoDbClient.builder()
                .region(Region.of(awsRegion))
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(awsAccessKey, awsSecretKey)))
                .build();
    }

    @Bean
    public DynamoDbEnhancedClient dynamoDbEnhancedClient(DynamoDbClient dynamoDbClient) {
        return DynamoDbEnhancedClient.builder()
                .dynamoDbClient(dynamoDbClient)
                .build();
    }
}

 

PostRepository 수정

@Repository
@RequiredArgsConstructor
public class PostRepository {

    private final DynamoDbEnhancedClient dynamoDbEnhancedClient;
    private static final String TABLE_NAME = "post";

    public Post save(Post post) {
        post.setId(UUID.randomUUID());
        post.setCreateDate(LocalDateTime.now().toString());

        DynamoDbTable<Post> table = dynamoDbEnhancedClient.table(TABLE_NAME, BeanTableSchema.create(Post.class));
        PutItemEnhancedRequest<Post> putItemEnhancedRequest = PutItemEnhancedRequest.builder(Post.class)
                .item(post)
                .build();

        table.putItem(putItemEnhancedRequest);

        return post;
    }
}

전체 데이터 조회하기(findAll())

PostRepository

    ...

    public List<Post> findAll() {
        DynamoDbTable<Post> table = dynamoDbEnhancedClient.table(TABLE_NAME, BeanTableSchema.create(Post.class));
        ScanEnhancedRequest scanEnhancedRequest = ScanEnhancedRequest.builder().build();
        PageIterable<Post> scan = table.scan(scanEnhancedRequest);

        return scan.items().stream().toList();
    }
}

 

PostService

    ...
    
    public List<Post> findAll() {
        return postRepository.findAll();
    }
}

 

PostController

    ...

    @GetMapping("")
    @ResponseBody
    public List<Post> posts() {
        return postService.findAll();
    }

}

단건 조회하기

- 파티션 키와 정렬 키 정보가 있어야 한다. => 조합이 곧 유니크 키

 

Post

    ...

    @DynamoDbSortKey
    public String getCreateDate() {
        return createDate;
    }

}

 

PostRepository

    ...

    public Optional<Post> findByIdAndCreateDate(String id, String createDate) {
        DynamoDbTable<Post> table = dynamoDbEnhancedClient.table(TABLE_NAME, TableSchema.fromBean(Post.class));

        Key key = Key.builder()
                .partitionValue(id)
                .sortValue(createDate)
                .build();

        Post post = table.getItem(
                (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key));

        return Optional.ofNullable(post);
    }

}

 

PostService

    ...

    public Optional<Post> findByIdAndCreateDate(String id, String createDate) {
        return postRepository.findByIdAndCreateDate(id, createDate);
    }

}

 

PostController

    ...

    @GetMapping("{id}/{createDate}")
    @ResponseBody
    public Post post(@PathVariable String id, @PathVariable String createDate) {
        return postService.findByIdAndCreateDate(id, createDate).orElse(null);
    }

}