Hibernate: Deleting Objects

It might look like this is turning into a Hibernate blog… maybe it’s just a phase I’m going through. This last week I ran into a place in some code where I wanted to write a query to delete a number of rows from the database. Deleting a single row using Hibernate is simple; get an instance of the persistent object you want to delete (ie: a Book, etc..) and an instance of the Session object and then called the delete(Object) method:

long bookid = 12;
Session sess = HibernateFactory.currentSession();
Object book = sess.load(Book.class, bookid);

Easy. Now, if you wanted to delete all the computer books for some reason, you’d have to first query the database using Hibernate to get a Collection of books, then iterate over the books, calling delete(Object object) on each one.

Collection books = BookFactory.getComputerBooks();
Session sess = HibernateFactory.currentSession();
for (Iterator i = books.iterator(); i.hasNext();) {
  Book book = (Book)i.next();

It’s easier than that though. The Session object has a delete(String query) method that I originally thought took a standard SQL ‘delete from table where…’ statement. After fussing with it for a bit, I read the documentation which says: “Delete all objects returned by the query. Return the number of objects deleted.”. Aha! Instead of calling delete() on each one, you use a SQL (or a HQL) statement that fetches the objects and then pass the results directly to the delete method:

Session sess = HibernateFactory.currentSession();
sess.delete("select book FROM org.mycompany.Book as book where type = 'technical'");

Just another example of how Hibernate makes it easier to work with relational databases.