IBM®
Skip to main content
    Country/region [select]      Terms of use
 
 
    
     Home      Products      Services & solutions      Support & downloads      My account     
 
developerworks > My developerWorks >  Dashboard > WebSphere eXtreme Scale V6.1 User Guide > ... > Basic EntityManager tutorial > Basic EntityManager tutorial step 5
developerWorks
Log In   View a printable version of the current page.
Overview Connect Spaces Forums Wikis
Basic EntityManager tutorial step 5
Added by Chris.D.Johnson, last edited by saif.patel@us.ibm.com on Jan 11, 2009  (view change)
Labels: 

Getting Started Examples Reference API documentation

See the WebSphere eXtreme Scale Wiki for links to eXtreme Scale Version 7.0 documentation.
If you log in with your developerWorks ID, you can leave comments and feedback for the development team.

This tutorial illustrates how to develop a local, in-memory ObjectGrid that stores order information for an online retail store.

Step 5 expands on the previous step to demonstrate how to use an ObjectGrid 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 signals the ObjectGrid 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 wasn't 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();
}

Finding the Entity using an Index

In the previous example, the ObjectMap with the name that coincides with the Order entity is found, and the index is then retrieved from it for the date attribute. The ObjectGrid automatically creats the index when the entity registers with the ObjectGrid, and the ObjectGrid initializes.

Each entity has its own ObjectMap instance, but ObjectGrid does not store the entity object instances in the ObjectMaps. Instead, ObjectGrid extracts the data from the entity by using the entity's accessor methods or fields, and stores them in a tuple object. When the ObjectGrid APIs are used to access an entity's ObjectMap, the keys and values in the map are always in the tuple format. For more information on tuples, see Using a Loader with entity maps and tuples.

When you invoke the dateIndex.findGreaterValue() method, the index return all of the keys that match the find criteria. In this case, an iterator with tuple keys is returned.

The find method is aware of the tuple format, so you can use the tuple key that is returned from the index to find the entity instead of extracting the key data out of the tuple. After you find the Order entity by using a key that is returned by the index, you must verify that the entity still satisfies the criteria. Because indexes do not hold any locks, the entity might be modified before you are able to update it.

When using the optimistic locking strategy, which is the default for all entities and maps, the version of the entity will not be retrieved until the find operation is performed. If another thread updates the entity between the time you alter it and commit the transaction, an OptimisticCollisionException is issued.

Pessmistic and Optimistic locking strategies

If you use the pessimistic locking strategy, the find method receives shared lock on the entity that prevents anyone else from updating it. Alternatively, the findForUpdate method receives an upgradeable lock, which prevents possible deadlocks with other threads. When planning to update an entity with the pessimistic lock strategy, first acquire an upgradeable lock.

Updating and removing entities

After you find the Order entity that you want to remove and you verify that it meets the removal criteria, add the items back into the inventory and remove the order from the cache.

Because the Order entity specifies the cascade remove option on the OrderLine relationship, all OrderLine entities are automatically removed when the Order is removed. However, you must manually update any other entities that have references to the Order or OrderLine entities.

For example, if the Customer entity has a reference to the Order entity, manually remove the Order entity from the Customer entity's collection or list of orders. Otherwise, the entity causes errors in the cache, such as a broken link in which the entity has a key for an entity that does not exist. When the entity becomes managed, the ObjectGrid logs a warning, CWPRJ1022W, that indicates a broken reference. The entity, however, can still be found. Edit the reference by updating the attributes of the entity, and then commit the transaction.

When you commit, and flush, the transaction, the Order and OrderLine entities are removed, and the Customer and Item entities are updated.

Previous Step Next Step

Wiki Disclaimer and License
© Copyright IBM Corporation 2007,2009. All Rights Reserved.


 
    About IBM Privacy Contact