Search
Tweets
Recent Changes
« Cascade Those Style Sheets | Main | Don't Mind Me. »
Thursday
Sep222005

Hibernate and all-delete-orphan

My current project utilizes Hibernate to abstract away the database access. I'm very happy with it, as any performance sensitive spots can easily be implemented with straight JDBC.

Anyway, there is one thing that I'd like to clear up. When you represent an object's relationships with a Set, you add something like this to the entities map:







This tells says that the containing class has a property creditCards that contains CreditCards. You are now free to manipulate the Set with the normal collections API, and when you save the object, the state of it's children will be saved to the database. This includes the act of deleting the parent if you supply the 'all-delete-orphan' setting to cascade. It tells Hibernate to delete any children that will orphaned by the deletion of the parent.

All of this bliss dependent, however, upon your session knowing about these relationships. If you create these entities independent of each other and save them, the session won't just go trudging back to the database and check for you.

The proper way to save something like this is:

Organization o = new Organization();
// Fill o with data
CreditCard cc = new CreditCard();
// Fill cc with data
cc.setOrganization(cc);
HashSet cards = new HashSet();
cards.add(cc);
o.setCreditCards(cards);
DAOFactory.getOrganizationDAO().save(o);

The Organization object 'o' that you just saved will now be fully aware of it's state, and you can successfully perform a o.getCreditCards().contains(cc)!

This is much different from the old school JDBC DAO method, where you probably saved each individual object. If I'm the only one, I just didn't get it. ;) So... I'm off to fix all my unit tests.

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>