Exception in Hibernate (Don't change the reference to a collection with cascade="all-delete-orphan")
I am getting a weird problem in hibernate. I am using hibernate and spring in my project.
Problem is I am having a parent child relation, and when I try to update the parent I am getting the exception
Caused by: org.hibernate.HibernateException: Don't change the reference to a collection with cascade="all-delete-orphan"
Following are the mappings :
Parent :
<set name="kittens" fetch="join" lazy="false"
inverse="true" cascade="all-delete-orphan">
<key>
<column name="ID" precision="22" scale="0"
not-null="true" />
</key>
<one-to-many
class="kitten" />
</set>
Child :
<composite-id name="id" class="kittenId">
<key-property name="kittenId" type="java.lang.Long">
<column name="Kitten_ID" precision="22" scale="0" />
</key-property>
<key-many-to-one name="cat" class="cat">
<c开发者_开发问答olumn name="ID" precision="22" scale="0" />
</key-many-to-one>
</composite-id>
I found in a forum and tried changing like
public void setKittens(Set kittens) {
this.kittens.clear();
this.kittens.addAll(kittens);
}
But now I am facing
org.hibernate.PropertyAccessException: Exception occurred inside setter of Kittens
Any help will be appreciated pls.
I had same problem. In my case problem was, that I, by mistake, instead of update(Entinty e)
called save(Entity e)
and got this error.
You should distinguish between situations when you call setKittens()
in order to replace contents of collection, and when Hibernate calls setKittens()
in order to initialize the property. I guess now you are getting NullPointerException
in the latter case, since this.kittens
is null
. If so, you can do this:
public void setKittens(Set kittens) {
if (this.kittens == null) {
this.kittens = kittens;
} else {
this.kittens.clear();
this.kittens.addAll(kittens);
}
}
Have you checked if the variable kittens is instantiated? Maybe it can be null and a NullPointerException is ocurring. You can try to debug inside the setKittens too.
I never used hibernate with xml, only annotations. So sorry if I said something stupid.
you should consider using merge() instead of using update();
And add "orphanRemoval = true" to one-to-many relationship like this:
class IngredientMaterial{
@OneToMany(mappedBy = "ingredientMaterial", fetch = FetchType.EAGER, cascade = CascadeType.ALL
, orphanRemoval = true //delete disassociated crowdSuggestion
)
private List<IngredientCrowdSuggestion> crowdSuggestions;
}
and use
merge(ngredientMaterial);
精彩评论