You can do this by using and EventListener that listens on "delete" events.
I've written an example from the top of my head so sorry if it doesn't compile or run, however it should give you a hint.
Basically you can create a subclass DefaultDeleteEventListener, override onDelete(DeleteEvent event) and plug it into your sessionfactory. It makes it a lot easier if you create a superclass or interface to identify objects that should have this behavior, in my example "SoftDeletable".
Code:
/** superclass (or make it an interface if you want) for all your domain classes
* that should be "flagged/soft" deleted when deleted instead of "hard" deleted.
*/
public class SoftDeletable {
private Boolean deleted;
....
}
/** plug this listener into hibernate (config below) */
public class SoftDeleteEventListener extends DefaultDeleteEventListener
public void onDelete(DeleteEvent event) {
Object toDelete = event.getObject();
// "soft delete" objects that inherit this behaviour
if( toDelete instanceof SoftDeletable ) {
Session session = event.getSession();
// set delete-flag and update object.
(( toDelete ) SoftDeletable).setDeleted( Boolean.TRUE );
session.update( toDelete );
} else {
// Proceed with normal delete for other objects
super.onDelete( event );
}
}
}
Hibernate configuration
Code:
<hibernate-configuration>
<session-factory>
...
<event type="delete">
<listener class="foo.bar.SoftDeleteEventListener"/>
</event>
</session-factory>
</hibernate-configuration>