As luck would have it, right after the blog post about creating history records went up on "In Relation To..." (
http://blog.hibernate.org/cgi-bin/blosxom.cgi/2004/06/19/), we've got a requirement to implement something like this. Unfortunately, database triggers were nixed, so we're left looking at Interceptors or Lifecycle callbacks.
I took a look at the History Interceptor article on the wiki (
http://www.hibernate.org/195.html), but I'm a little skeptical of the code. I've used it as a template to implement my own interceptor, but my own unit tests show that it doesn't work. I've got a Parent and Child classes, which are in a parent-child relationship, and each of them has a collection of Activity objects (ParentActivity and ChildActivity types, respectively, mapped to different tables). These are mapped as bidirectional parent-child relationships as well.
The problem is that, although the create activities are inserted and can be found by subsequent transactions, the update activities for the parent object are not saved. I think this is because the activities are being added back to the object in postFlush() by the interceptor I copied, so they're not getting flushed, since they'd only be saved based on the cascade from the Parent object to its ParentActivity collection.
I can get this to work, however, if I cheat... I've got my Session in a ThreadLocal, so I can get it even inside the Interceptor, where it's not supposed to be used (at least that was the impression I got). If I explicitly save the new Activity objects I'm creating, then things get inserted successfully. I'm just worried that I'm doing something that's not guaranteed to work, and that I may experience strange errors later.
Anyone have any insight for me? All of this is a little sample app I've been using and adding to to test Hibernate features, so I'm ok to post any / all of it here...