【问题标题】:Delete Parent and Child in One-Many Mapping in Hibernate在 Hibernate 的一对多映射中删除父项和子项
【发布时间】:2013-02-28 21:51:45
【问题描述】:

父表

    <property name="buyerGroupName"    type="string"        column="BUYER_GROUP_NAME" />
    <property name="description"       type="string"        column="DESCRIPTION" />
    <property name="approvalPathId"    type="int"           column="APPROVAL_PATH_ID" />
    <property name="active"            type="int"           column="ACTIVE" />
    <property name="createdOn"         type="timestamp">
            <column name="CREATED_ON" length="20" not-null="true" />
    </property>

    <set name="buyers" table="buyers" cascade="all" >
        <key>
            <column name="BG_ID" not-null="true" />
        </key>
        <one-to-many class="com.sg.beans.Buyers" />
    </set>


</class>
  </hibernate-mapping>

子表映射

  <hibernate-mapping>
<class name="com.sg.beans.Buyers" table="buyers" >
    <id  name="id" type="int"  column="ID">
        <generator class="increment" />
    </id>

    <property    name="loginId" type="int" column="LOGIN_ID" />

    <many-to-one name="buyerGroup" class="com.sg.beans.BuyerGroup"    fetch="select" cascade="all"  >
        <column name="BG_ID" not-null="true" />
    </many-to-one> 

</class>
     </hibernate-mapping>

删除方法..传递父对象删除

   public Boolean deleteBuyerGroup(BuyerGroup bg){

    try {
        session.delete(bg);
        session.getTransaction().commit();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

以下是错误

   buyerGroup.getBuyerGroupId()1

   Hibernate: update buyers set BG_ID=null where BG_ID=?
   org.hibernate.exception.ConstraintViolationException: Column 'BG_ID' cannot be null

我进行了调试并确保将 BG_ID 设置为预期的值...请帮助!

【问题讨论】:

    标签: hibernate orm hibernate-mapping


    【解决方案1】:

    我认为您必须在父实体的映射上使用 cascade 属性上的 all,delete-orphan 值。 您还必须通过在父实体映射上设置inverse="true" 来设置双向关系的负责人。

    【讨论】:

    • 你放了吗:cascade='all,delete-orphan'
    • 是的,我在 parent.hbm 文件中为买家标签做了所有级联
    • 我编辑了我的答案,因为我看到您的映射中没有 inverse="true"
    • 我确实添加了它,现在它不会抛出任何错误..我在控制台中看到它正在运行删除查询..但是当我检查数据库 (MYSQL) 时,列仍然存在在父子表中
    • 我认为现在您可能有交易问题,请查看mkyong.com/hibernate/hibernate-transaction-handle-example
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    相关资源
    最近更新 更多