我想在DynamoDB中为我的对象实现更改历史记录。这样做的简单方法是指定"对象id"作为哈希和"更新的时间"作为范围键。但是,java sdk不允许注释键始终自动生成(在没有注释方便的情况下更改值似乎可行)。为什么呢?
示例代码:
@DynamoDBTable(tableName = "data")
public class Person {
public static void main(String[] args) {
AmazonDynamoDBClient client = new AmazonDynamoDBClient()
.withEndpoint("http://localhost:8000");
DynamoDBMapper mapper = new DynamoDBMapper(client);
TableUtils.deleteTableIfExists(client, mapper.generateDeleteTableRequest(Person.class));
TableUtils.createTableIfNotExists(client, mapper.generateCreateTableRequest(Person.class)
.withProvisionedThroughput(new ProvisionedThroughput(1L, 1L))
);
Person person = new Person();
person.setPersonId("abc");
mapper.save(person);
mapper.save(person);
TableUtils.deleteTableIfExists(client, mapper.generateDeleteTableRequest(Person.class));
}
@DynamoDBHashKey
private String personId;
@DynamoDBRangeKey
@DynamoDBAutoGeneratedTimestamp
private Long updated;
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public Long getUpdated() {
return updated;
}
public void setUpdated(Long updated) {
this.updated = updated;
}
}
例外:
Exception in thread "main" com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: Field com.dynamodb.testpackage.Person[updated] must not have auto-generated key with ALWAYS strategy
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperFieldModel$Builder.build(DynamoDBMapperFieldModel.java:797)
at com.amazonaws.services.dynamodbv2.datamodeling.StandardModelFactories$SchemaFactory.newTableModel(StandardModelFactories.java:118)
at com.amazonaws.services.dynamodbv2.datamodeling.StandardModelFactories$SchemaFactory.getTableModel(StandardModelFactories.java:86)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.getTableModel(DynamoDBMapper.java:401)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.generateCreateTableRequest(DynamoDBMapper.java:2432)
at com.dynamodb.testpackage.Person.main(Person.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
答案 0 :(得分:0)
您的用例不典型。通常,您不希望更改对象的哈希和范围键。事实上,我会劝阻它。
事实上,对于DynamoDB,项目的唯一特征是它的键(无论是仅分区键还是分区+范围键),因此更改范围键实质上会创建一个新项目,从技术上讲,它不是更新。
我不确定这是否准确表示 原因导致SDK中不支持混合@DynamoDBAutoGeneratedTimestamp
和@DynamoDBRangeKey
,但这肯定是一个原因。