Reputation: 447
I've got two classes, ProductConfiguration and SubProduct.
I want to replace the subproducts on the configuration, which I do in this way:
productConfiguration.getSubProducts().clear();
productConfiguration.getSubProducts().addAll(newSubProducts);
In doing this, Hibernate attempts to set the ID of the parent (the product configuration) to null, and then update the row in the database. This fails, as the parent ID is a foreign key, and therefore not nullable.
The mapping from ProductConfiguration to 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"/>
Upvotes: 0
Views: 217
Reputation: 447
The solution here is simple. I forgot to add an inverse statement to the product configuration side.
<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>
Upvotes: 0
Reputation: 30813
if the foreign key is not nullable you probably want to delete SubProducts which have no parent:
<bag name="subProducts" cascade="all-delete-orphan" ...
Update: to prevent the updates of the foreign key you can do
<bag name="subProducts" inverse="true" ...
// and
for (SubProduct sub : productConfiguration.getSubProducts())
{
sub.setParentProduct(null);
}
productConfiguration.getSubProducts().clear();
productConfiguration.getSubProducts().addAll(newSubProducts);
Upvotes: 1