I have the following situation: One table of Customers can have many projects. the relationship is bidirectional.
I am trying to delete a customer from a list of Customers and if the customers has already assigned with some projects I got an exception:
" that I cannot delete or update a parent row: a foreign key constraint fails"
meaning that I have first to delete the relevant projects.
However I need a solution for that case and I suppose the problem is related with mapping files. Here are the mapping files:
<hibernate-mapping>
<class name="com.nisid.entities.Customers" table="customers">
<meta attribute="class-description"> This class contains the customer records. </meta>
<id name="customerId" type="int" column="customerId">
<generator class="native"/>
</id>
<many-to-one name="fkuser" class="com.nisid.entities.Worker"
fetch="select">
<column name="fk_userID" not-null="true"/>
</many-to-one>
<set name="projects" lazy="false" inverse="true" fetch="select" cascade="all" >
<key column="customerId" not-null="true"/>
<one-to-many class="com.nisid.entities.Project"/>
</set>
<property name="customerName" column="customerName" type="string"/>
<property name="customerSurname" column="customerSurname" type="string"/>
<property name="adress" column="adress" type="string"/>
<property name="email" column="email" type="string"/>
<property name="phoneNumber" column="contactDetails" type="string"/>
</class>
</hibernate-mapping>
And the child:
<hibernate-mapping>
<class name="com.nisid.entities.Project" table="projects">
<meta attribute="class-description"> This class contains the project records. </meta>
<id name="projectId" type="int" column="projectId">
<generator class="native">
</generator>
</id>
<many-to-one name="fkCustomer" class="com.nisid.entities.Customers"
fetch="select">
<column name="customerId" not-null="true"/>
</many-to-one>
<set name="payments" lazy="true" fetch="select" inverse="true" >
<key column="projectId" not-null="true"/>
<one-to-many class="com.nisid.entities.Payment"/>
</set>
<property name="projectName" column="projectName" type="string" />
<property name="projectDescription" column="description" type="string"/>
</class>
</hibernate-mapping>
Change the cascade on your projects set to "all-delete-orphan" instead of "all"