Hello I'm having a problem with a parent child relationship where the parent also stores a link to the most recent child added.
The Schema looks like this:
Parent
id
Children
LastChild
Child
id
Parent
Here is the hibernate modeling information for the parent class:
/**
* Returns a set of all Children
* @hibernate.set table="child" lazy="true" cascade="all" inverse="true"
* @hibernate.collection-key column="parent_id"
* @hibernate.collection-one-to-many class="com.kshep.Child"
*/
public Set getChildren() {
return m_children;
}
/**
* Returns the last child added to the children list
* @return the last child added to the children list
* @hibernate.many-to-one column="last_child_id" cascade="save-update"
*/
public Child getLastChild() {
return m_lastChild;
}
Here is how I've currently modeled the child class
/**
* Gets the parent object
* @hibernate.many-to-one non-null="true" column="parent_id" cascade="none"
*/
public Parent getParent() {
return m_parent;
}
The SQL generates exactly the way I want it. The problem comes when I try to delete a Parent object. When deleting the parent, first it tries to delete all of the Children since the Set is an inverse relationship. The problem is that when it tries to delete the children it violates the foreign key constraint on the lastChild column since lastChild would be pointing to an ID that no longer exists... Is there a way to make hiberate automatically null that field out before it tries to delete the children? I supposed I could null it out myself, but in my case the parent is also a child of another different parent class.
It just seems like this should be a pretty common problem, but I didn't see anything in the FAQ or forums that handle this specific case. If I get rid of the lastChild column relationship everything works fine. The reason I'd like this is because the lastChild will get references quite frequently and the Set of Children belonging to one parent is going to grow large. So I wanted to avoid having to load the entire Set just to find the latest Child.
Any help would be greatly appreciated.
Thanks,
-Keith
|