Deleting Objects

If you’ve made changes to your data-creation script and want to start with a “clean slate” in the form of an empty database so you can test them, all you need to do is run ant schema again. This will drop and recreate the Track table in a pristine and empty state. Don’t do it unless you mean it!

If you want to be more selective about what you delete, you can either do it through SQL commands in the HSQLDB UI (ant db), or you can make a variant of the query-test example that retrieves the objects you want to get rid of. Once you’ve got a reference to a persistent object, passing it to the Session’s delete() method will remove it from the database:

session.delete(aTrack);

You’ve still got at least one reference to it in your program, until aTrack goes out of scope or gets reassigned, so conceptually the easiest way to understand what delete() does is to think of it as turning a persistent object back into a transient one.

Another way to delete is to write an HQL deletion query that matches multiple objects. This lets you delete many persistent objects at once, whether or not you have them as objects in memory, without writing your own loop. A Java-based alternative to ant schema, and a slightly less violent way of clearing out all the tracks, would therefore be something like this:

Query query = session.createQuery("delete from Track");                 
query.executeUpdate(); 

Warning

Don’t forget that regardless of which of these approaches you use, you’ll need to wrap the data-manipulation ...

Get Getting Started with Hibernate 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.