Java Reference
In-Depth Information
Deleting Entities
In order to allow convenient removal of entities from the database, the Session interface pro-
vides a delete() method, as follows:
public void delete(Object object) throws HibernateException
This method takes a persistent object as an argument. The argument can also be a tran-
sient object with the identifier set to the id of the object that needs to be erased.
In the simplest form, in which you are simply deleting an object with no associations to
other objects, this is straightforward; but many objects do have associations with other objects.
To allow for this, Hibernate can be configured to allow deletes to cascade from one object to its
associated objects.
For instance, consider the situation in which you have a parent with a collection of child
objects, and you would like to delete them all. The easiest way to handle this is to use the
cascade attribute on the collection's element in the Hibernate mapping. If you set the cascade
attribute to delete or all , the delete will be cascaded to all of the associated objects. Hiber-
nate will take care of deleting these for you—deleting the parent erases the associated objects.
Hibernate 3 also supports bulk deletes (see Listing 4-5), where your application executes
a DELETE HQL statement against the database. These are very useful for deleting more than
one object at a time because each object does not need to be loaded into memory just to be
deleted.
Listing 4-5. A Bulk Delete Using a Hibernate Query
session.createQuery("delete from User").executeUpdate();
Network traffic is greatly reduced, as are the memory requirements compared to those for
individually issuing a delete() call against each entity identifier.
n Caution Bulk deletes do not cause cascade operations to be carried out. If cascade behavior is needed,
you will need to carry out the appropriate deletions yourself, or use the session's delete() method.
Cascading Operations
When you perform one of the operations described in this chapter on an entity, the opera-
tions will not be performed on the associated entities unless you explicitly tell Hibernate to
perform them.
For example, the following code will fail when we try to commit the transaction because
the message entity that is associated with the Email entity has not been persisted into the
database—and so the Email entity cannot be accurately represented (with its foreign key onto
the appropriate message row) in its table.
Search WWH ::




Custom Search