如何将DynamoDB扫描结果添加到对象列表中?

5

我正在对DynamoDB表执行扫描,然后需要将返回的项目的相应属性添加到类型为User的列表中(User具有一个名为User(String uuid)的构造函数)。当前代码成功扫描了DB并返回了扫描结果的List。但是我的迭代似乎由于某种原因返回null。

    AmazonDynamoDBClient client = dynamoClient.getDynamoClient();
    DynamoDBMapper mapper = new DynamoDBMapper(client);

    try {
        DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();

        Map<String, Condition> scanFilter = new HashMap<String, Condition>();
        Condition scanCondition = 
            new Condition().withComparisonOperator(ComparisonOperator.NOT_NULL);
        scanFilter.put("uuid", scanCondition);
        scanExpression.setScanFilter(scanFilter);

        List scanResults = mapper.scan(UserAccounts.class, scanExpression);

        for (Iterator it = scanResults.iterator(); it.hasNext();) {
            //User user = (User) it.next();
            allUserSummary.add(new User(scanResults.get(1).toString()));
        }
    } catch (Exception e) {
        // TODO
    }

将打印语句放在for循环内部,看看是否打印出用户信息...同时确保这是在postconstructor中完成的,而不是在allUserSummary的getter方法中完成的。 - Daniel
@Daniel 我可以确认问题来自于这一行代码:allUserSummary.add(new User(scanResults.get(1).toString())); 如果我在迭代器中加入一个打印语句,我会得到正确数量的用户返回,但显然这些用户是空的! - tarka
1个回答

3

我建议您开始使用现代紧凑的列表迭代方式,即通过for-each循环,它有助于避免在使用旧的迭代样式时出现许多常见错误:

[...]

The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error. Here is how the example looks with the for-each construct:

void cancelAll(Collection<TimerTask> c) {
    for (TimerTask t : c)
        t.cancel();
}
将此应用于您的用例,大致如下:
    List<UserAccounts> scanResults = mapper.scan(UserAccounts.class, scanExpression);

    for (UserAccounts userAccounts : scanResults) {
        allUserSummary.add(new User(userAccounts.toString()));
    }

如果这个方法还没有起作用,那么它可能会提示实际的错误,因为你的代码假设类UserAccountstoString()方法返回 uuid ,但有时并非如此。通常的做法是拥有一个getKey()getUuidAttribute()方法和相应的注解@DynamoDBHashKey@DynamoDBAttribute,就像在Class DynamoDBMapper中所示的示例一样:

@DynamoDBTable(tableName = "UserAccounts")
 public class UserAccounts{     
     private String key; // or uuid right away

     @DynamoDBHashKey
     public String getKey() {
         return key;
     }

     public void setKey(String key) {
         this.key = key;
     }

     // ...
 }

这显然会根据您的示例产生以下结果:
    List<UserAccounts> scanResults = mapper.scan(UserAccounts.class, scanExpression);

    for (UserAccounts userAccounts : scanResults) {
        allUserSummary.add(new User(userAccounts.getKey()));
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接