Hibernate: how to null out foreign key references when deleting an entity?
843859Aug 12 2007 — edited Aug 12 2007We use Spring/Hibernate3 in our app, and ran into kind of a bummer of a problem. We have a relationship that is many-to-one (e.g. Student -> School). This is represented by a schoolId on the Student table. When we delete the school through the Hibernate layer, we are immediately receiving foreign key constraints because Hibernate does not null out the Students' schoolId columns where applicable.
What we'd like to see happen is something like this:
1. SchoolDAO.delete(id)
Hibernate: UPDATE Student set schoolId = NULL where schoolId = ?
Hibernate: DELETE from School where id = ?
But what we're actually seeing is:
1. SchoolDAO.delete(id)
Hibernate: DELETE from School where id = ?
And hence the foreign key constraints.
Was wondering if someone else here has run into this. Someone on the Hibernate forums suggested using an Interceptor, but the Hibernate3 interceptors don't give us access to the Session to allow us to do a bulk update to null out these references. Apparently the interceptor javadoc says that the interceptor is basically there to change properties on the object in question and should not involve the session at all.
We then looked at implementing an Event, and that worked, but was not called for every cascade deleted event. We have a lot of cascade activity in our database, so that was a little disappointing.
We had briefly considered manually nulling out that FK in the DAO itself, but that would not work with the large amount of Hibernate driven cascade deletion that goes on in our app (Hibernate does not call our DAO every time it cascade deletes an entity).
Would greatly appreciate any pointers on this subject. We're hoping that others have run into this as well.
thanks.