Hibernate version: 3.0.2 (in JBoss 4.0.2)
Hello,
i'm having some problems when deleting objects (inverse side) that are involved in relationships. Maybe someone could help me out or give me some hints?
Suppose i have a one-to-many relationship between Company and Employee. Company is declared as the inverse side and the Employee table contains a Foreign Key to the Company. When the Company is deleted (hSession.delete(company)) the foreign key will not be removed from the Employee table.
If this would be a many-to-many relationship, with a CompaniesEmployees table for this relationship, the rows containing the deleted Company's ID will not be removed from this table.
I understand that this is caused because of using the inverse="true" attribute in the Company's mapping file. Probably i should clear up the Company's relationships before deleting it:
Code:
public class Company
{
...
public void clearAllYourInverseRelationships()
{
employees.clear();
// This probably isn't sufficient ...
}
}
company.clearAllYourInverseRelationships();
hSession.delete(company);
But what should i do when the Company is deleted because of a cascade delete? In this case i don't know when it will be deleted so i can't call the clearAllYourInverseRelationships() method.
Maybe i could write a PreDeleteEventListener that will be called when something is deleted by a cascade delete. This listener could call the clearAllYourInverseRelationships() method. But this would mean my POJO's would have to imlement an interface that defines the clearAllYourInverseRelationships() method. Furthermore i'm using JBoss 4.0.2 so it can't add event listeners using the Hibenate MBean in a har (yet?).
And isn't all of this going a bit to far?
Maybe i'm looking at this wrong and should i take a completely other approach??? I can of course always remove the inverse="true" from my mapping files but its use is recommended.
With one-to-many and many-to-many relationships i don't get exceptions because of this problem, there is just data in the database that shouldn't be there but maybe for certain applications i could live with that.
Unfortunately things are worse for one-to-one relationships with foreign keys. Suppose i have a bi-directional one-to-one relationship between Employee and Address, using the following mapping files:
Code:
<class name="myapp.Employee">
...
<many-to-one name="address" column="address" unique="true"/>
</class>
<class name="myapp.Address">
...
<one-to-one name="employee" property-ref="address"/>
</class>
Fist problem is that when i delete an Address the foreign key isn't removed from the Employee table although there is no inverse side here!?
Secondly when i call getAddress() on an Employee of which the Address was deleted before i get an Exception, which is quite normal since an Address with that key doesn't exist any more.
What am i doing wrong here?
Any help with this would be much appreciated!
Regards,
Erwin