This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
Hibernate-owned entity instances no longer reference collections with CASCADE = “all-delete-orphan”
I encountered the following problem when trying to update my entity:
"A collection with cascade= "all-delete-orphan" was no longer referenced by the owning entity instance".
Copy the code
I have a parent entity that has Set <… >. When I try to update it, I get all the references to set for this collection and set them.
The following code represents my mapping:
@OneToMany(mappedBy = "parentEntity", fetch = FetchType.EAGER)
@Cascade({ CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public Set<ChildEntity> getChildren(a) {
return this.children;
}
Copy the code
I tried to just clean up Set <.. “> < p style =” max-width: 100%; clear: both;
Answer 1:
Check all the places to assign content to subclass entities. The link you referenced clearly indicates the process of creating a new HashSet, but you may encounter this error when you reassign the HashSet. Such as:
public void setChildren(Set<SonEntity> aSet)
{
this.sonEntities = aSet; //This will override the set that Hibernate is tracking.
}
Copy the code
Typically, you only want to “new” the collection once in the constructor. Every time you want to add or remove something from the list, you must modify the contents of the list rather than assign a new list.
To add child nodes:
public void addChild(SonEntity aSon)
{
this.sonEntities.add(aSon);
}
Copy the code
Delete child nodes:
public void removeChild(SonEntity aSon)
{
this.sonEntities.remove(aSon);
}
Copy the code
Answer 2:
This method
public void setChildren(Set<SonEntity> aSet) {
this.sonEntities = aSet;
}
Copy the code
If parentEntity is separated, the method is valid, and then we update it
However, if the entity is not separated by context (that is, the lookup and update operations are in the same transaction), then the following is valid.
public void setChildren(Set<SonEntity> aSet) {
//this.sonEntities = aSet; //This will override the set that Hibernate is tracking.
this.sonEntities.clear();
if(aSet ! =null) {
this.sonEntities.addAll(aSet); }}Copy the code