在hibernate中以一对多关系从父表中删除记录

时间:2013-08-04 16:31:34

标签: nhibernate-mapping hibernate-onetomany delete-record

我有以下情况: 一个客户表可以有很多项目。这种关系是双向的。

我正在尝试从客户列表中删除客户,如果客户已经分配了一些项目我得到了例外:

  

“我无法删除或更新父行:外键约束失败”

意思是我先删除相关项目。

但是我需要一个针对该案例的解决方案,我想这个问题与映射文件有关。以下是映射文件:

<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>

孩子:

<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>

1 个答案:

答案 0 :(得分:0)

将项目集上的级联更改为&#34; all-delete-orphan&#34;而不是&#34;所有&#34;