Retrieving Multiple Objects

Some indices result in the retrieval of multiple objects. For example, MANY_TO_ONE indices can result in more than one object for any given key. When this is the case, you must iterate over the resulting set of objects in order to examine each object in turn.

To retrieve a set of objects, use the SecondaryIndex.subIndex() method to return an EntityIndex class object. Then, use that object's entities() method to obtain an EntityCursor. This cursor allows you to iterate over the object set.

For example:

PrimaryIndex<String,Inventory> inventoryBySku =
    store.getPrimaryIndex(String.class, Inventory.class);

SecondaryIndex<String,String,Inventory> inventoryByName = 
    store.getSecondaryIndex(inventoryBySku, String.class, "itemName");

EntityCursor<Inventory> items = 
    inventoryByName.subIndex("Lemon").entities(); 

Now that we have the entity cursor, we can iterate over the resulting objects. Here we use the new Java 1.5 enhanced for notation to perform the iteration:

try {
    for (Inventory item : items) {
        // do something with each Inventory object "item"
    }
// Always make sure the cursor is closed when we are done with it.
} finally {
    items.close();
} 

Note that it is also possible to iterate over every entity object of a given type in the entity store. You do this using the entity's primary index, and then call its entities() method to obtain an EntityCursor:

PrimaryIndex<String,Inventory> inventoryBySku =
    store.getPrimaryIndex(String.class, Inventory.class);

EntityCursor<Inventory> items = inventoryBySku.entities(); 
            
try {
    for (Inventory item : items) {
        // do something with each Inventory object "item"
    }
// Always make sure the cursor is closed when we are done with it.
} finally {
    items.close();
}