UpdateJSON.updateTableWithoutQuery()
UpdateJSON.updateTableWithoutQuery()
メソッドは、表のすべての行を反復処理し、更新する適切な行を探します。
これは、nullフィールドの継続的なチェックが必要であるため、最も複雑な更新メソッドです。次のコードはすべて、表の行を取得するためにのみ使用されます。実際の更新操作は、UpdateJSON.updateZipCode()によって実行されます。
// Utility method. Given a MapValue and a field name,
// return the field as a MapValue. Used by
// updateTableWithoutQuery()
private MapValue getMV(MapValue mv, String field) {
FieldValue fv = null;
if ((fv = mv.get(field)) != null)
return fv.asMap();
return null;
}
// Update the zip code found on all Boston home addresses
// to "02102-1000"
//
// Because we are not using an index, we must iterate over
// every row in the table, modifying the rows with Boston home
// addresses.
private void updateTableWithoutQuery(KVStore kvstore) {
TableAPI tableH = kvstore.getTableAPI();
Table myTable = tableH.getTable("personContacts");
PrimaryKey pkey = myTable.createPrimaryKey();
TableIterator<Row> iter =
tableH.tableIterator(pkey, null, null);
try {
while (iter.hasNext()) {
int account = 0;
Row row = iter.next();
FieldValue fv = null;
try {
account = row.get("account").asInteger().get();
MapValue mv = row.get("person").asMap();
MapValue mvaddress = getMV(mv, "address");
if (mvaddress != null) {
MapValue mvhome = getMV(mvaddress, "home");
if (mvhome != null) {
fv = mvhome.get("city");
if (fv != null) {
if (fv.toString()
.equalsIgnoreCase("Boston"))
updateZipCode(tableH,
row,
"home",
"02102-1000");
}
}
}
} catch (ClassCastException cce) {
System.out.println("Data error: ");
System.out.println("Account " + account +
"has a missing or incomplete person field");
// If this is thrown, then the "person" field
// doesn't exist for the row.
}
}
} finally {
if (iter != null) {
iter.close();
}
}
System.out.println("Updated a table without using a query.");
}