Java용 SDK 버전 1과 버전 2 간의 DynamoDB 매핑 APIs 변경 사항 - AWS SDK for Java 2.x

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Java용 SDK 버전 1과 버전 2 간의 DynamoDB 매핑 APIs 변경 사항

클라이언트 만들기

사용 사례 V1 V2

일반 인스턴스화

AmazonDynamoDB standardClient = AmazonDynamoDBClientBuilder.standard() .withCredentials(credentialsProvider) .withRegion(Regions.US_EAST_1) .build(); DynamoDBMapper mapper = new DynamoDBMapper(standardClient);
DynamoDbClient standardClient = DynamoDbClient.builder() .credentialsProvider(ProfileCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(standardClient) .build();

최소 인스턴스화

AmazonDynamoDB standardClient = AmazonDynamoDBClientBuilder.standard(); DynamoDBMapper mapper = new DynamoDBMapper(standardClient);
DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.create();

속성 변환기 사용*

DynamoDBMapper mapper = new DynamoDBMapper(standardClient, attributeTransformerInstance);
DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(standardClient) .extensions(extensionAInstance, extensionBInstance) .build();

*V2의 확장은 대략 V1의 속성 변환기에 해당합니다. 이 확장을 사용하여 DynamoDB 향상된 클라이언트 작업 사용자 지정 섹션에는 V2의 확장에 대한 자세한 정보가 포함되어 있습니다.

DynamoDB 테이블/인덱스에 대한 매핑 설정

V1에서는 빈 주석을 통해 DynamoDB 테이블 이름을 지정합니다. 공장 메서드인 V2에서는 원격 DynamoDB 테이블DynamoDbTable을 나타내는의 인스턴스를 table()생성합니다. table() 메서드의 첫 번째 파라미터는 DynamoDB 테이블 이름입니다.

사용 사례 V1 V2

Java POJO 클래스를 DynamoDB 테이블에 매핑

@DynamoDBTable(tableName ="Customer") public class Customer { ... }
DynamoDbTable<Customer> customerTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class));

DynamoDB 보조 인덱스에 매핑

  1. 인덱스를 나타내는 POJO 클래스를 정의합니다.

    • 인덱스가 있는 테이블의 이름을 @DynamoDBTable 제공하는 로 클래스에 주석을 추가합니다.

    • @DynamoDBIndexHashKey 및 선택적으로를 사용하여 속성에 주석을 추가합니다@DynamoDBIndexRangeKey.

  2. 쿼리 표현식을 생성합니다.

  3. 인덱스를 나타내는 POJO 클래스에 대한 참조를 사용하여 쿼리합니다. 예

    mapper.query(IdEmailIndex.class, queryExpression)

    여기서 IdEmailIndex는 인덱스의 매핑 클래스입니다.

V1 query서드에 대해 설명하는 DynamoDB 개발자 안내서의 섹션에 전체 예제가 나와 있습니다.

  1. (GSI의 경우) 및 @DynamoDbSecondaryPartitionKey ( 및 GSI 또는 LSI의 경우)를 사용하여 POJO 클래스의 속성@DynamoDbSecondarySortKey에 주석을 추가합니다. 예:

    @DynamoDbSecondarySortKey(indexNames = "IdEmailIndex") public String getEmail() { return this.email; }
  2. 인덱스에 대한 참조를 검색합니다. 예:

    DynamoDbIndex<Customer> customerIndex = customerTable.index("IdEmailIndex");
  3. 인덱스를 쿼리합니다.

이 가이드의 보조 인덱스 사용 섹션에서는 자세한 정보를 제공합니다.

테이블 작업

이 섹션에서는 대부분의 표준 사용 사례에서 V1과 V2가 다른 작업 APIs에 대해 설명합니다.

V2에서는 단일 테이블과 관련된 모든 작업이 향상된 클라이언트가 아닌 DynamoDbTable 인스턴스에서 호출됩니다. 향상된 클라이언트에는 여러 테이블을 대상으로 지정할 수 있는 메서드가 포함되어 있습니다.

아래 테이블 작업이라는 테이블에서 POJO 인스턴스를 item 또는와 같은 특정 유형이라고 합니다customer1. V2 예제의 경우 이름이 인 인스턴스tableDynamoDbTable 인스턴스에 대한 참조를 반환enhancedClient.table()하는를 이전에 호출한 결과입니다.

대부분의 V2 작업은 표시되지 않은 경우에도 유창한 소비자 패턴으로 호출할 수 있습니다. 예:

Customer customer = table.getItem(r → r.key(key)); or Customer customer = table.getItem(r → r.key(k -> k.partitionValue("id").sortValue("email")))

V1 작업의 경우 테이블 작업(아래)에는 모든 오버로드된 양식이 아니라 일반적으로 사용되는 양식 중 일부가 포함됩니다. 예를 들어 load() 메서드에는 다음과 같은 오버로드가 있습니다.

mapper.load(Customer.class, hashKey) mapper.load(Customer.class, hashKey, rangeKey) mapper.load(Customer.class, hashKey, config) mapper.load(Customer.class, hashKey, rangeKey, config) mapper.load(item) mapper.load(item, config)

테이블 작업(아래)은 일반적으로 사용되는 양식을 보여줍니다.

mapper.load(item) mapper.load(item, config)
테이블 작업
사용 사례 V1 V2

DynamoDB 테이블에 Java POJO 쓰기

DynamoDB 작업: PutItem, UpdateItem

mapper.save(item) mapper.save(item, config) mapper.save(item, saveExpression, config)

V1에서 DynamoDBMapperConfig.SaveBehavior 및 주석은 호출할 하위 수준 DynamoDB 메서드를 결정합니다. 일반적으로 UpdateItemSaveBehavior.CLOBBER 및를 사용할 때를 제외하고 호출됩니다SaveBehavior.PUT. 자동 생성된 키는 특별한 사용 사례이며 경우에 따라 PutItemUpdateItem가 모두 사용됩니다.

table.putItem(putItemRequest) table.putItem(item) table.putItemWithResponse(item) //Returns metadata. updateItem(updateItemRequest) table.updateItem(item) table.updateItemWithResponse(item) //Returns metadata.

DynamoDB 테이블에서 Java POJO로 항목 읽기

DynamoDB 작업: GetItem

mapper.load(item) mapper.load(item, config)
table.getItem(getItemRequest) table.getItem(item) table.getItem(key) table.getItemWithResponse(key) //Returns POJO with metadata.

DynamoDB 테이블에서 항목 삭제

DynamoDB 작업: DeleteItem

mapper.delete(item, deleteExpression, config)
table.deleteItem(deleteItemRequest) table.deleteItem(item) table.deleteItem(key)

DynamoDB 테이블 또는 보조 인덱스 쿼리 및 페이지 매김 목록 반환

DynamoDB 작업: Query

mapper.query(Customer.class, queryExpression) mapper.query(Customer.class, queryExpression, mapperConfig)
table.query(queryRequest) table.query(queryConditional)

동기화 응답 및 PagePublisher.subscribe() 비동기 응답에 반환된PageIterable.stream()(지연 로드) 사용

DynamoDB 테이블 또는 보조 인덱스 쿼리 및 목록 반환

DynamoDB 작업: Query

mapper.queryPage(Customer.class, queryExpression) mapper.queryPage(Customer.class, queryExpression, mapperConfig)
table.query(queryRequest) table.query(queryConditional)

동기화 응답 및 PagePublisher.items.subscribe() 비동기 응답에 반환된PageIterable.items()(지연 로드) 사용

DynamoDB 테이블 또는 보조 인덱스 스캔 및 페이지 매김 목록 반환

DynamoDB 작업: Scan

mapper.scan(Customer.class, scanExpression) mapper.scan(Customer.class, scanExpression, mapperConfig)
table.scan() table.scan(scanRequest)

동기화 응답 및 PagePublisher.subscribe() 비동기 응답에 반환된PageIterable.stream()(지연 로드) 사용

DynamoDB 테이블 또는 보조 인덱스 스캔 및 목록 반환

DynamoDB 작업: Scan

mapper.scanPage(Customer.class, scanExpression) mapper.scanPage(Customer.class, scanExpression, mapperConfig)
table.scan() table.scan(scanRequest)

동기화 응답 및 PagePublisher.items.subscribe() 비동기 응답에 반환된PageIterable.items()(지연 로드) 사용

배치의 여러 테이블에서 여러 항목 읽기

DynamoDB 작업: BatchGetItem

mapper.batchLoad(Arrays.asList(customer1, customer2, book1)) mapper.batchLoad(itemsToGet) // itemsToGet: Map<Class<?>, List<KeyPair>>
enhancedClient.batchGetItem(batchGetItemRequest) enhancedClient.batchGetItem(r -> r.readBatches( ReadBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addGetItem(i -> i.key(k -> k.partitionValue(0))) .build(), ReadBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addGetItem(i -> i.key(k -> k.partitionValue(0))) .build())) // Iterate over pages with lazy loading or over all items from the same table.

배치의 여러 테이블에 여러 항목 쓰기

DynamoDB 작업: BatchWriteItem

mapper.batchSave(Arrays.asList(customer1, customer2, book1))
enhancedClient.batchWriteItem(batchWriteItemRequest) enhancedClient.batchWriteItem(r -> r.writeBatches( WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addPutItem(item1) .build(), WriteBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addPutItem(item2) .build()))

배치의 여러 테이블에서 여러 항목 삭제

DynamoDB 작업: BatchWriteItem

mapper.batchDelete(Arrays.asList(customer1, customer2, book1))
enhancedClient.batchWriteItem(r -> r.writeBatches( WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addDeleteItem(item1key) .build(), WriteBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addDeleteItem(item2key) .build()))

배치에서 여러 항목 쓰기/삭제

DynamoDB 작업: BatchWriteItem

mapper.batchWrite(Arrays.asList(customer1, book1), Arrays.asList(customer2))
enhancedClient.batchWriteItem(r -> r.writeBatches( WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addPutItem(item1) .build(), WriteBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addDeleteItem(item2key) .build()))

트랜잭션 쓰기 수행

DynamoDB 작업: TransactWriteItems

mapper.transactionWrite(transactionWriteRequest)
enhancedClient.transactWriteItems(transasctWriteItemsRequest)

트랜잭션 읽기 수행

DynamoDB 작업: TransactGetItems

mapper.transactionLoad(transactionLoadRequest)
enhancedClient.transactGetItems(transactGetItemsRequest)

쿼리의 일치하는 항목 수 가져오기

DynamoDB 작업: Query 사용 Select.COUNT

mapper.count(Customer.class, queryExpression)
// Get the count from query results. PageIterable<Customer> pageIterable = customerTable.query(QueryEnhancedRequest.builder() .queryConditional(queryConditional) .select(Select.COUNT) .build()); Iterator<Page<Customer>> iterator = pageIterable.iterator(); Page<Customer> page = iterator.next(); int count = page.count(); // For a more concise approach, you can chain the method calls: int count = customerTable.query(QueryEnhancedRequest.builder() .queryConditional(queryConditional) .select(Select.COUNT) .build()) .iterator().next().count();

스캔의 일치하는 항목 수 가져오기

DynamoDB 작업:Scan 사용 Select.COUNT

mapper.count(Customer.class, scanExpression)
// Get the count from scan results. PageIterable<Customer> pageIterable = customerTable.scan(ScanEnhancedRequest.builder() .filterExpression(filterExpression) .select(Select.COUNT) .build()); Iterator<Page<Customer>> iterator = pageIterable.iterator(); Page<Customer> page = iterator.next(); int count = page.count(); // For a more concise approach, you can chain the method calls: int count = customerTable.scan(ScanEnhancedRequest.builder() .filterExpression(filterExpression) .select(Select.COUNT) .build()) .iterator().next().count();

DynamoDB에서 POJO 클래스에 해당하는 테이블 생성

DynamoDB 작업: CreateTable

mapper.generateCreateTableRequest(Customer.class)

이전 문은 하위 수준 테이블 생성 요청을 생성합니다. 사용자는 DynamoDB 클라이언트createTable에서를 호출해야 합니다.

table.createTable(createTableRequest) table.createTable(r -> r.provisionedThroughput(defaultThroughput()) .globalSecondaryIndices( EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_1") .projection(p -> p.projectionType(ProjectionType.ALL)) .provisionedThroughput(defaultThroughput()) .build()));

DynamoDB에서 병렬 스캔 수행

DynamoDB 작업: SegmentTotalSegments 파라미터 Scan 포함

mapper.parallelScan(Customer.class, scanExpression, numTotalSegments)

사용자는 작업자 스레드를 처리하고 각 세그먼트에 scan 대해를 호출해야 합니다.

table.scan(r -> r.segment(0).totalSegments(5))

Amazon S3를 DynamoDB와 통합하여 지능형 S3 링크 저장

mapper.createS3Link(bucket, key) mapper.getS3ClientCache()

Amazon S3와 DynamoDB를 결합하므로 지원되지 않습니다.

클래스 및 속성 매핑

V1과 V2 모두에서 빈 스타일 주석을 사용하여 클래스를 테이블에 매핑합니다. V2는 변경 불가능한 클래스 작업과 같이 특정 사용 사례에 대한 스키마를 정의하는 다른 방법도 제공합니다.

빈 주석

다음 표에는 V1 및 V2에 사용되는 특정 사용 사례에 대해 동등한 빈 주석이 나와 있습니다. Customer 클래스 시나리오는 파라미터를 설명하는 데 사용됩니다.

V2의 주석과 클래스 및 열거는 낙타 사례 규칙을 따르고 'DynamoDB'가 아닌 'DynamoDb'를 사용합니다.DynamoDB

사용 사례 V1 V2
클래스를 테이블에 매핑
@DynamoDBTable (tableName ="CustomerTable")
@DynamoDbBean @DynamoDbBean(converterProviders = {...})
테이블 이름은 DynamoDbEnhancedClient#table() 메서드를 호출할 때 정의됩니다.
클래스 멤버를 테이블 속성으로 지정
@DynamoDBAttribute(attributeName = "customerName")
@DynamoDbAttribute("customerName")
클래스 멤버를 해시/파티션 키로 지정
@DynamoDBHashKey
@DynamoDbPartitionKey
클래스 멤버를 범위/정렬 키로 지정
@DynamoDBRangeKey
@DynamoDbSortKey
클래스 멤버를 보조 인덱스 해시/파티션 키로 지정
@DynamoDBIndexHashKey
@DynamoDbSecondaryPartitionKey
클래스 멤버를 보조 인덱스 범위/정렬 키로 지정
@DynamoDBIndexRangeKey
@DynamoDbSecondarySortKey
테이블에 매핑할 때이 클래스 멤버 무시
@DynamoDBIgnore
@DynamoDbIgnore
클래스 멤버를 자동 생성된 UUID 키 속성으로 지정
@DynamoDBAutoGeneratedKey
@DynamoDbAutoGeneratedUuid

이를 제공하는 확장은 기본적으로 로드되지 않으므로 클라이언트 빌더에 확장을 추가해야 합니다.

클래스 멤버를 자동 생성된 타임스탬프 속성으로 지정
@DynamoDBAutoGeneratedTimestamp
@DynamoDbAutoGeneratedTimestampAttribute

이를 제공하는 확장은 기본적으로 로드되지 않으므로 클라이언트 빌더에 확장을 추가해야 합니다.

클래스 멤버를 자동 증분 버전 속성으로 지정
@DynamoDBVersionAttribute
@DynamoDbVersionAttribute

이를 제공하는 확장은 자동으로 로드됩니다.

클래스 멤버를 사용자 지정 변환이 필요한 것으로 지정
@DynamoDBTypeConverted
@DynamoDbConvertedBy
다른 속성 유형으로 저장할 클래스 멤버 지정
@DynamoDBTyped(<DynamoDBAttributeType>)

AttributeConverter 구현을 사용합니다. V2는 일반적인 Java 유형을 위한 많은 내장 변환기를 제공합니다. 자체 사용자 지정 AttributeConverter 또는를 구현할 수도 있습니다AttributeConverterProvider. 이 설명서의 제어 속성 변환 섹션을 참조하세요.

DynamoDB 문서(JSON 스타일 문서) 또는 하위 문서로 직렬화할 수 있는 클래스 지정
@DynamoDBDocument
향상된 문서 API를 사용합니다. 다음 리소스를 참조하세요.

V2 추가 주석

사용 사례 V1 V2
Java 값이 null인 경우 클래스 멤버를 NULL 속성으로 저장하지 않도록 지정합니다. N/A
@DynamoDbIgnoreNulls
모든 속성이 null인 경우 클래스 멤버를 빈 객체로 지정 N/A
@DynamoDbPreserveEmptyObject
클래스 멤버에 대한 특별 업데이트 작업 지정 N/A
@DynamoDbUpdateBehavior
변경할 수 없는 클래스 지정 N/A
@DynamoDbImmutable
클래스 멤버를 자동 증분 카운터 속성으로 지정 N/A
@DynamoDbAtomicCounter

이 기능을 제공하는 확장은 자동으로 로드됩니다.

구성

V1에서는 일반적으로 인스턴스를 사용하여 특정 동작을 제어합니다DynamoDBMapperConfig. 매퍼를 생성하거나 요청할 때 구성 객체를 제공할 수 있습니다. V2에서 구성은 작업에 대한 요청 객체에 따라 다릅니다.

사용 사례 V1 V1의 기본값 V2
DynamoDBMapperConfig.builder()
배치 로드/쓰기 재시도 전략
.withBatchLoadRetryStrategy(loadRetryStrategy)
.withBatchWriteRetryStrategy(writeRetryStrategy)
실패한 항목 재시도 기본에서 재시도 전략을 구성합니다DynamoDBClient. 이 설명서의 에서 재시도 동작 구성 AWS SDK for Java 2.x 섹션을 참조하세요.
일관된 읽기
.withConsistentReads(CONSISTENT)
EVENTUAL 기본적으로 일관된 읽기는 읽기 작업에 대해 false입니다. 요청 객체.consistentRead(true)에서 로 재정의합니다.
마샬러/언마샬러 세트가 포함된 변환 스키마
.withConversionSchema(conversionSchema)

정적 구현은 이전 버전과의 이전 버전과의 호환성을 제공합니다.

V2_COMPATIBLE 해당 사항 없음. 이는 DynamoDB(V1)의 최신 버전이 데이터 형식을 저장한 방식을 참조하는 레거시 기능이며,이 동작은 향상된 클라이언트에서 유지되지 않습니다. DynamoDB V1의 동작 예제는 부울을 부울 대신 숫자로 저장하는 것입니다.
테이블 이름
.withObjectTableNameResolver() .withTableNameOverride() .withTableNameResolver()

정적 구현은 이전 버전과의 이전 버전과의 호환성을 제공합니다.

클래스에서 주석 또는 추측 사용

테이블 이름은 DynamoDbEnhancedClient#table() 메서드를 호출할 때 정의됩니다.

페이지 매김 로드 전략
.withPaginationLoadingStrategy(strategy)

옵션은 LAZY_LOADING, EAGER_LOADING또는 입니다. ITERATION_ONLY

LAZY_LOADING
  • 반복만 기본값입니다. 다른 V1 옵션은 지원되지 않습니다.

  • 다음을 사용하여 V2에서 에이거 로드를 구현할 수 있습니다.

    List<Customer> allItems = customerTable.scan().items().stream().collect(Collectors.toList());
  • 로드 지연의 경우 액세스한 항목에 대한 자체 캐싱 로직을 구현해야 합니다.

지표 수집 요청
.withRequestMetricCollector(collector)
null 표준 DynamoDB 클라이언트를 빌드할 ClientOverrideConfigurationmetricPublisher()에서를 사용합니다.
동작 저장
.withSaveBehavior(SaveBehavior.CLOBBER)

옵션은 UPDATE, CLOBBER, PUT, APPEND_SET또는 입니다UPDATE_SKIP_NULL_ATTRIBUTES.

UPDATE

V2에서는 putItem() 또는를 updateItem() 명시적으로 호출합니다.

CLOBBER or PUT: v 2의 해당 작업이를 호출합니다putItem(). 특정 CLOBBER 구성은 없습니다.

UPDATE:에 해당 updateItem()

UPDATE_SKIP_NULL_ATTRIBUTES:에 해당합니다updateItem(). 요청 설정 ignoreNulls 및 주석/태그를 사용하여 업데이트 동작을 제어합니다DynamoDbUpdateBehavior.

APPEND_SET: 지원되지 않음

Type 변환기 팩토리
.withTypeConverterFactory(typeConverterFactory)
표준 유형 변환기

를 사용하여 빈에 설정

@DynamoDbBean(converterProviders = {ConverterProvider.class, DefaultAttributeConverterProvider.class})

작업별 구성

V1에서와 같은 일부 작업은 작업에 제출된 "표현" 객체를 통해 query()고도로 구성할 수 있습니다. 예:

DynamoDBQueryExpression<Customer> emailBwQueryExpr = new DynamoDBQueryExpression<Customer>() .withRangeKeyCondition("Email", new Condition() .withComparisonOperator(ComparisonOperator.BEGINS_WITH) .withAttributeValueList( new AttributeValue().withS("my"))); mapper.query(Customer.class, emailBwQueryExpr);

V2에서는 구성 객체를 사용하는 대신 빌더를 사용하여 요청 객체에 파라미터를 설정합니다. 예:

QueryEnhancedRequest emailBw = QueryEnhancedRequest.builder() .queryConditional(QueryConditional .sortBeginsWith(kb -> kb .sortValue("my"))).build(); customerTable.query(emailBw);

조건부

V2에서 조건부 및 필터링 표현식은 조건과 이름 및 필터의 매핑을 캡슐화하는 Expression 객체를 사용하여 표현됩니다.

사용 사례 운영 V1 V2
예상 속성 조건 save(), delete(), query(), scan()
new DynamoDBSaveExpression() .withExpected(Collections.singletonMap( "otherAttribute", new ExpectedAttributeValue(false))) .withConditionalOperator(ConditionalOperator.AND);
더 이상 사용되지 않습니다. ConditionExpression 대신를 사용합니다.
조건 표현식 delete()
deleteExpression.setConditionExpression("zipcode = :zipcode") deleteExpression.setExpressionAttributeValues(...)
Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", AttributeValues.stringValue("wrong")) .putExpressionValue(":value1", AttributeValues.stringValue("three")) .build(); DeleteItemEnhancedRequest request = DeleteItemEnhancedRequest.builder() .conditionExpression(conditionExpression).build();
필터 표현식 query(), scan()
scanExpression .withFilterExpression("#statename = :state") .withExpressionAttributeValues(attributeValueMapBuilder.build()) .withExpressionAttributeNames(attributeNameMapBuilder.build())
Map<String, AttributeValue> values = singletonMap(":key", stringValue("value")); Expression filterExpression = Expression.builder() .expression("name = :key") .expressionValues(values) .build(); QueryEnhancedRequest request = QueryEnhancedRequest.builder() .filterExpression(filterExpression).build();
쿼리에 대한 조건 표현식 쿼리()
queryExpression.withKeyConditionExpression()
QueryConditional keyEqual = QueryConditional.keyEqualTo(b -> b .partitionValue("movie01")); QueryEnhancedRequest tableQuery = QueryEnhancedRequest.builder() .queryConditional(keyEqual) .build();

유형 변환

기본 변환기

V2에서 SDK는 모든 일반 유형에 대한 기본 변환기 세트를 제공합니다. 전체 공급자 수준과 단일 속성 모두에서 유형 변환기를 변경할 수 있습니다. AttributeConverter API 참조에서 사용 가능한 변환기 목록을 찾을 수 있습니다.

속성에 대한 사용자 지정 변환기 설정

V1에서는 로 getter 메서드에 주석을 달@DynamoDBTypeConverted아 Java 속성 유형과 DynamoDB 속성 유형 간에 변환하는 클래스를 지정할 수 있습니다. 예를 들어 Java Currency 유형과 DynamoDB 문자열 간에 변환CurrencyFormatConverter하는는 다음 코드 조각과 같이 적용할 수 있습니다.

@DynamoDBTypeConverted(converter = CurrencyFormatConverter.class) public Currency getCurrency() { return currency; }

이전 코드 조각과 동일한 V2가 아래에 나와 있습니다.

@DynamoDbConvertedBy(CurrencyFormatConverter.class) public Currency getCurrency() { return currency; }
참고

V1에서는 속성 자체, 유형 또는 사용자 정의 주석에 주석을 적용할 수 있으며, V2는 주석을 getter에만 적용할 수 있도록 지원합니다.

유형 변환기 팩토리 또는 공급자 추가

V1에서는 고유한 유형 변환기 세트를 제공하거나 구성에 유형 변환기 팩토리를 추가하여 관심 있는 유형을 재정의할 수 있습니다. 유형 변환기 팩토리는를 확장하며DynamoDBTypeConverterFactory, 재정의는 기본 세트에 대한 참조를 가져와서 확장하여 수행됩니다. 다음 코드 조각은 이를 수행하는 방법을 보여줍니다.

DynamoDBTypeConverterFactory typeConverterFactory = DynamoDBTypeConverterFactory.standard().override() .with(String.class, CustomBoolean.class, new DynamoDBTypeConverter<String, CustomBoolean>() { @Override public String convert(CustomBoolean bool) { return String.valueOf(bool.getValue()); } @Override public CustomBoolean unconvert(String string) { return new CustomBoolean(Boolean.valueOf(string)); }}).build(); DynamoDBMapperConfig config = DynamoDBMapperConfig.builder() .withTypeConverterFactory(typeConverterFactory) .build(); DynamoDBMapper mapperWithTypeConverterFactory = new DynamoDBMapper(dynamo, config);

V2는 @DynamoDbBean 주석을 통해 유사한 기능을 제공합니다. 주문된의 체인 하나 AttributeConverterProvider 또는 하나를 제공할 수 AttributeConverterProvider있습니다. 자체 속성 변환기 공급자 체인을 제공하는 경우 기본 변환기 공급자를 재정의하고 속성 변환기를 사용하려면 체인에 포함해야 합니다.

@DynamoDbBean(converterProviders = { ConverterProvider1.class, ConverterProvider2.class, DefaultAttributeConverterProvider.class}) public class Customer { ... }

이 가이드의 속성 변환 섹션에는 V2에 대한 전체 예제가 포함되어 있습니다.