cascading when hibernating

July 21, 2007

There is a tree of objects, all of them nicely mapped to my favorite database. Will I turn on persistence cascading on all the relations? You bet I will! This is very important Hibernate feature, the ability to save root object and all the related child objects will be saved as well. It’s one of the most important selling points of any object-relational mapping tools or even object databases.

Unfortunately hibernate does not implement persistence by reachability (or transitive persistence) by default :( It requires explicit configuration, which means every time when there is one-to-x relation a developer has to consider whether he needs cascaded persistence or not. Surely there are some rare cases where transitive persistence is not desired but in most cases it is very important to set it up. Using ORM or object DB the expectation is that the object tree cascades persistence actions. When I save root object I expect it to be saved, not only some parts of it, but whole structure.

So whenever I see code like this (even test code):

session.save(book.getPublication());
session.save(book.getAuthor());
session.save(book);

I put delivering business values away and turn on refactoring mode, this line of code should do the whole magic:

session.save(book);

I like when saving an object really means saving it.