我试图通过服务向DynamoDB数据库添加多个条目,但是当执行代码时,只保存一个条目。这是我到目前为止所做的:
public int onStartCommand(Intent intent, int flags, int startId) {
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(), // Context
"us-east-1:851c121e-326d-4c9e-be47-fec40eb7b693", // Identity Pool ID
Regions.US_EAST_1 // Region
);
AmazonDynamoDB client = new AmazonDynamoDBClient(credentialsProvider);
Toast.makeText(this, "Adding To Database...", Toast.LENGTH_LONG).show();
CognitoCachingCredentialsProvider cognitoProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(), // Context
"us-east-1:851c121e-326d-4c9e-be47-fec40eb7b693", // Identity Pool ID
Regions.US_EAST_1 // Region
);
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(cognitoProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
String streamName = intent.getStringExtra("streamName");
String userCreated = intent.getStringExtra("userCreated");
ArrayList<String> selectedFriend = intent.getStringArrayListExtra("userInvolved");
intent.getStringExtra("comment");
for(int i = 0; i < selectedFriend.size(); i++){
Streams streams = new Streams();
streams.setStreamname(streamName);
streams.setUsercreated(userCreated);
streams.setUserinvolved(selectedFriend.get(i));
streams.setUnread(true);
streams.setDeleted(false);
mapper.save(streams);
}
}
就像我说的那样,只会保存一个条目。我被建议使用arraylist,但我不知道如何去做。有人可以帮忙吗?
感谢所有帮助。
编辑:Streams.java
类:
@DynamoDBTable(tableName = "Streams")
public class Streams{
private String streamname;
private String usercreated;
private String userinvolved;
private boolean unread;
private boolean deleted;
@DynamoDBAttribute(attributeName = "Stream_Name")
public String getStreamname() {
return streamname;
}
public void setStreamname(String streamname) {
this.streamname = streamname;
}
@DynamoDBHashKey(attributeName = "User_Created")
public String getUsercreated() {
return usercreated;
}
public void setUsercreated(String usercreated) {
this.usercreated = usercreated;
}
@DynamoDBAttribute(attributeName = "User_Involved")
public String getUserinvolved() {
return userinvolved;
}
public void setUserinvolved(String userinvolved) {
this.userinvolved = userinvolved;
}
@DynamoDBAttribute(attributeName = "Unread")
public boolean isUnread() {
return unread;
}
public void setUnread(boolean unread) {
this.unread = unread;
}
@DynamoDBAttribute(attributeName = "Deleted")
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}
答案 0 :(得分:2)
您的DynamoDB哈希键似乎是Stream类中的user created
字段。这是DynamoDB主键,它唯一标识DynamoDB表中的单个项目。
每次调用mapper.save(streams)
时,您都会覆盖在循环的上一次迭代中编写的项目,因为您似乎只在此处设置了user created
字段:
String userCreated = intent.getStringExtra("userCreated");
。
尝试使用唯一标识符(例如stream name
作为哈希键)。如果多个项具有相同的散列键,您还可以使用带有范围键的模式来创建(散列键,范围键)主键,以唯一标识DynamoDB表中的项。
答案 1 :(得分:0)
DynamodbMapper有一个批量保存方法,允许您批量保存多个对象。查看DynamoDBMapper.batchSave。