Subscribe to RSS Feed

Categories

Archives

Hibernate and all-delete-orphan

↓ skip to article

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.

Comments (No comments)

There are no comments for this post so far.

Post a comment