WebSphere eXtreme Scale Product Overview > Tutorials > Tutorials, examples, and samples > Entity manager tutorial
Entity manager tutorial: Updating and removing entries by using a query
You can update and remove entities by using a query.
Procedure
Update and remove entities by using a query.
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 order entity class is the same as it is in the previous example. The class still provides the @Index annotation, because the query string uses the date to find the entity. The query engine uses indices when they can be used.
public static void cancelOrdersUsingQuery(Session s) { // 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(); // Create a query that will find the order based on date. Since // we have an index defined on the order date, the query // will automatically use it. Query query = em.createQuery("SELECT order FROM Order order WHERE order.date >= ?1"); query.setParameter(1, cancelTime); Iterator<Order> orderIterator = query.getResultIterator(); while(orderIterator.hasNext()) { Order order = orderIterator.next(); // Verify that the order wasn't updated by someone else. // Since the query used an index, there was no lock on the row. if(order != null && order.date.getTime() >= cancelTime.getTime()) { for(OrderLine line : order.lines) { // Add the item back to the inventory. line.item.quantityOnHand += line.quantity; line.quantity = 0; } em.remove(order); } } em.getTransaction().commit(); }Like the previous example, the cancelOrdersUsingQuery method intends to cancel all orders that were submitted in the past minute.
To cancel the order, you find the order using a query, add the items in the order back into the inventory, and remove the order and associated line items from the system.
Parent topic
Entity manager tutorial: Overview
Previous topic:
Entity manager tutorial: Updating and removing entries with an index