Product overview > Tutorials, examples, and samples > Entity manager tutorial



Entity manager tutorial: Updating and removing entries with an index

Use an index to find, update, and remove entities.


Procedure

Update and remove entities by using an index. Use an index to find, update, and remove entities. In the following examples, the Order entity class is updated to use the @Index annotation. The @Index annotation signalsWebSphere eXtreme Scale to create a range index for an attribute. The name of the index is the same name as the name of the attribute and is always a MapRangeIndex index type.

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


Parent topic:

Entity manager tutorial: Overview


Previous topic:

Entity manager tutorial: Updating entries


Next topic:

Entity manager tutorial: Updating and removing entries by using a query


+

Search Tips   |   Advanced Search