有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate和从列表中删除

我有两个类,ProductConfiguration和SubProduct

我想替换配置上的子管道,我是这样做的:

productConfiguration.getSubProducts().clear();
productConfiguration.getSubProducts().addAll(newSubProducts);

在执行此操作时,Hibernate尝试将父级(产品配置)的ID设置为null,然后更新数据库中的行。这将失败,因为父ID是外键,因此不可为null

从ProductConfiguration到SubProduct的映射:

<bag name="subProducts"
     table="sub_product"
     cascade="all-delete-orphan"
     access="field"
     lazy="false">
    <key column="parent_id"/>
    <one-to-many class="com.conscius.cpt.core.product.SubProduct"/>
</bag>

<many-to-one name="parentProduct"
             class="com.conscius.cpt.core.product.ProductConfiguration"
             column="parent_id"
             access="field"
             not-null="true"
             cascade="none"/>

共 (2) 个答案

  1. # 1 楼答案

    如果外键不可为空,则可能需要删除没有父级的子管道:

    <bag name="subProducts" cascade="all-delete-orphan" ...
    

    更新:为了防止外键的更新,你可以这样做

    <bag name="subProducts" inverse="true" ...
    
    // and
    for (SubProduct sub : productConfiguration.getSubProducts())
    {
        sub.setParentProduct(null);
    }
    productConfiguration.getSubProducts().clear();
    productConfiguration.getSubProducts().addAll(newSubProducts);
    
  2. # 2 楼答案

    这里的解决方案很简单。我忘了在产品配置端添加反向语句

    <bag name="subProducts"
         table="sub_product"
         cascade="all-delete-orphan"
         access="field"
         lazy="false">
        <key column="parent_id"/>
        <one-to-many class="com.conscius.cpt.core.product.SubProduct"/>
    </bag>