10.10. Delete By Query

Queries are useful not only for finding objects, but for efficiently deleting them as well. For example, you might delete all records created before a certain date. Rather than bring these objects into memory and delete them individually, EJB allows you to perform a single bulk delete based on EJBQL criteria.

[Warning]Warning

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

Delete by query uses the same EJBQL syntax as normal queries, with one exception: begin your query string with the delete keyword instead of the select keyword. To then execute the delete, you call the following Query method:

public int executeUpdate ();

This method returns the number of objects deleted. The following example deletes all subscriptions whose expiration date has passed.

Example 10.1. Delete by Query

Query q = em.createQuery ("delete s from Subscription s where s.subscriptionDate < :today");
q.setParameter ("today", new Date ());
int deleted = q.executeUpdate ();