Cayenne User Documentation
Deleting Objects

As discussed before, an object must be deleted in the DataContext to trigger a removal of the corresponding row from the database on commit. There are few simple ways to delete individual objects and collections of objects. Quite naturally, a delete operation changes the object state to PersistenceState.DELETED. However there maybe other consequences of such operation for the overall object graph. Such consequences are controlled via delete rules configured for object relationships. Properly configuring delete rules will simplify the application code, as you no longer need to track related objects and do the right thing with them. Other delete rule effects are discussed for each DataContext deletion method individually.

##### Deleting a single object

    DataContext context = ...;
    Artist artist = ....;

    // this will trigger delete rules for artist, if any
    context.deleteObject(artist);

##### Deleting a collection of objects

    DataContext context = ...;
    Artist artist = ....;

    context.deleteObjects(artist.getPaintings());

##### Deleting in an Iterator

This case can be complicated if an iteration is performed over a relationship list and an object being deleted has a nullify delete rule. Such combination may result in ConcurrencyModificationExceptions as collection underlying the iterator is being modified. If ALL objects in the collection have to be deleted, use "deleteObjects()" method shown above - it will do the right thing. If only a subset of collection objects has to be deleted, you can use the following technique:

    DataContext context = ...;
    Artist artist = ....;

    Iterator it = artist.getPaintings().iterator();
    while(it.hasNext()) {
       DataObject object = it.next();

       if(some_condition) {
          // jump ahead of the delete rule and unset the relationship
          it.remove();

          // now do the actual delete
          context.deleteObject(object);
       }
    }

.
Copyright ©2001-2007 Apache Software Foundation