You can use an index to find, update, and remove entities.
Order.java
@Entity
public class Order
{
@Id String orderNumber;
@Index java.util.Date date;
@OneToOne(cascade=CascadeType.PERSIST) Customer customer;
@OneToMany(cascade=CascadeType.ALL, mappedBy="order")
@OrderBy("lineNumber") List<OrderLine> lines; }
The following example demonstrates how to cancel all orders
that are submitted within the last minute. Find the order by using
an index, add the items in the order back into the inventory, and
remove the order and the associated line items from the system.public static void cancelOrdersUsingIndex(Session s)
throws ObjectGridException {
// Cancel all orders that were submitted 1 minute ago
java.util.Date cancelTime = new
java.util.Date(System.currentTimeMillis() - 60000);
EntityManager em = s.getEntityManager();
em.getTransaction().begin();
MapRangeIndex dateIndex = (MapRangeIndex)
s.getMap("Order").getIndex("date");
Iterator<Tuple> orderKeys = dateIndex.findGreaterEqual(cancelTime);
while(orderKeys.hasNext()) {
Tuple orderKey = orderKeys.next();
// Find the Order so we can remove it.
Order curOrder = (Order) em.find(Order.class, orderKey);
// Verify that the order was not updated by someone else.
if(curOrder != null && curOrder.date.getTime() >= cancelTime.getTime()) {
for(OrderLine line : curOrder.lines) {
// Add the item back to the inventory.
line.item.quantityOnHand += line.quantity;
line.quantity = 0;
}
em.remove(curOrder);
}
}
em.getTransaction().commit();
}