10.11. Update By Query

Similar to bulk deletes, it is sometimes necessary to perform updates against a large number of queries in a single operation, without having to bring all the instances down to the client. Rather than bring these objects into memory and modifying them individually, EJB allows you to perform a single bulk update based on EJBQL criteria.

[Warning]Warning

This feature is only partially implemented in this Kodo preview. In particular, note that objects update by query are not properly cleared from Kodo's data cache. Until this feature is fully implemented, we recommend isolating classes subject to update by query in a separate cache which can be evicted manually or through timeouts. These shortcomings will be resolved in a future preview.

Update by query uses the same EJBQL syntax as normal queries, except that the query string begins with the update keyword instead of select. To execute the update, you call the following Query method:

public int executeUpdate ();

This method returns the number of objects updated. The following example updates all subscriptions whose expiration date has passed to have the "paid" field set to true..

Example 10.2. Update by Query

Query q = em.createQuery ("update Subscription s set s.paid = :paid where s.subscriptionDate < :today");
q.setParameter ("today", new Date ());
q.setParameter ("paid", true);
int updated = q.executeUpdate ();