4

我正在对 DynamoDB 表执行扫描,然后我需要将返回的项目中的相应属性添加到类型列表中UserUser具有单个构造函数User(String uuid))。该代码当前成功扫描了数据库并返回了一个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
    }
4

1 回答 1

3

我建议您通过For-Each 循环开始使用现代且紧凑的列表迭代,这有助于避免使用旧迭代样式时的许多常见错误:

[...]

迭代器只是混乱。此外,这是犯错的机会。迭代器变量在每个循环中出现 3 次:这是两次出错的机会。for-each 结构消除了混乱和出错的机会。下面是使用 for-each 构造的示例的外观:

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()));
    }

如果这还不起作用,它也可能暗示实际错误,只要您的代码假定toString()of 类UserAccounts返回uuid,情况可能会也可能不会。通常的方法是使用getKey()orgetUuidAttribute()方法和相应的注释@DynamoDBHashKeyor @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()));
    }
于 2012-05-13T14:23:30.187 回答