This section explains how to model relationship delete rules and how to delete individual objects as well as sets of objects. Also demonstrated the use of DataObjectUtils class to run a query.
Before we discuss the API for object deletion, lets go back to CayenneModeler and set up some delete rules. Doing this is optional but will simplify correct handling of the objects related to deleted objects.
In the Modeler go to "Artist" ObjEntity, "Relationships" tab and select "Cascade" for the "paintings" relationship delete rule:
Repeat this step for other relationships:
- For Gallery set "paintings" relationship to be "Nullify", as a painting can exist without being displayed in a gallery.
- For Painting et both relationships rules to "Nullify".
Now save the mapping, and refresh the project in Eclispe.
While deleting objects is possible via SQL, qualifying a delete on one or more IDs, a more common way in Cayenne (or ORM in general) is to get a hold of the object first, and then delete it via the context. Let's use utility class DataObjectUtils to find an artist:
Now let's delete the artist:
Since we set up "Cascade" delete rule for the Artist.paintings relationships, Cayenne will automatically delete all paintings of this artist. So when your run the app you'll see this output:
Next Step: Tutorial Webapp