DynamoDbAtomicCounter始终返回null问题排查求助
DynamoDB AtomicCounter 返回null问题排查与解决
我按照AWS官方文档使用AtomicCounter生成唯一ID,但两个计数器字段始终返回null。
初始代码
实体类代码
@DynamoDbBean public class CustomerDocument { private String root; private Long updateCounter; private Long customCounter; @DynamoDbPartitionKey public String getRoot() { return this.root; } public void setRoot(String id) { this.root = id; } @DynamoDbAtomicCounter public Long getUpdateCounter() { return this.updateCounter; } public void setUpdateCounter(Long counter) { this.updateCounter = counter; } @DynamoDbAtomicCounter(delta = 5, startValue = 10) public Long getCustomCounter() { return this.customCounter; } public void setCustomCounter(Long counter) { this.customCounter = counter; } }
仓库层调用代码
CustomerDocument document = new CustomerDocument(); document.setRoot(root); customerTable.updateItem(document); CustomerDocument retrievedCustomer = customerTable.getItem(document); retrievedCustomer.getUpdateCounter(); // null retrievedCustomer.getCustomCounter(); // null customerTable.updateItem(document); retrievedCustomer = orderCounterTable.getItem(document); retrievedCustomer.getUpdateCounter(); // null retrievedCustomer.getCustomCounter(); // null
编辑后问题
修改代码后,调用updateItem仍返回null,仅返回包含id的对象:
修改后的代码
public CustomerDocument nextCounter(String root) { CustomerDocument document = new CustomerDocument(); document.setId(root); CustomerDocument item = orderCounterTable.getItem(document); if (item == null) { CustomerDocument defaultDocument = new CustomerDocument(); defaultDocument.setId(root); defaultDocument.setCount(1L); customerTable.putItem(defaultDocument); return defaultDocument; } else { CustomerDocument newDocument = new CustomerDocument(); newDocument.setId(item.getId()); return customerTable.updateItem(newDocument); } }
返回结果
{ "id": "20042024" }
问题原因及解决办法
updateItem默认不返回更新属性
DynamoDB Enhanced Client的updateItem方法默认不会返回AtomicCounter修改后的字段值,需显式配置返回更新后的完整项目。调整
updateItem调用逻辑
使用UpdateItemEnhancedRequest指定返回所有更新后的属性,无需额外调用getItem:UpdateItemEnhancedRequest<CustomerDocument> request = UpdateItemEnhancedRequest.builder(CustomerDocument.class) .item(document) .returnValues(ReturnValue.ALL_NEW) // 返回更新后的完整对象 .build(); CustomerDocument updatedDoc = customerTable.updateItem(request); // updatedDoc中的updateCounter和customCounter字段已更新统一实体类字段映射
检查实体类的setter/getter与字段名一致性,比如编辑后代码中使用setId,但初始类是setRoot,确保分区键字段映射统一,避免因字段不匹配导致属性未更新。正确初始化计数器
首次创建项目时,putItem不会触发AtomicCounter逻辑,只有updateItem才会执行计数器递增。若需初始化起始值,可在putItem时直接设置对应字段值,后续updateItem会基于该值递增。
内容的提问来源于stack exchange,提问作者Youcef LAIDANI
相关产品推荐
相关产品推荐

