我有两个类,ProductConfiguration 和 SubProduct。
我想替换配置上的子产品,我这样做:
productConfiguration.getSubProducts().clear();
productConfiguration.getSubProducts().addAll(newSubProducts);
在此过程中,Hibernate 尝试将父级(产品配置)的 ID 设置为 null,然后更新数据库中的行。这会失败,因为父 ID 是外键,因此不能为空。
从 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"/>
最佳答案
如果外键不可为空,您可能想要删除没有父项的子产品:
<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);
关于java - hibernate 并从列表中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8837030/