1

So after adding orphanRemoval = true to @OneToMany relationship in one of my entities, I get the following exception when trying to save a new or delete an existing entity which references the one with orphanRemoval = true attribute.

The exception I get is:

A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: fully.qualified.path.to.the.property.with.orphanRemoval.setToTrue

One to many relationship is specified like this:

  @OneToMany(
  targetEntity = MyEntity.class,
  fetch = FetchType.LAZY,
  mappedBy = "mappingField_",
  orphanRemoval = true,
  cascade = CascadeType.ALL)
  private List<MyEntity> myEntities_= new ArrayList<>();

I get exception when I try to save and flush the entity:

myEntityRepository_.saveAndFlushAndRefresh(myEntityInstance);

I couldn't find lot of information about this.

whatamidoingwithmylife
  • 1,119
  • 1
  • 16
  • 35
  • Have you checked [this answer](https://stackoverflow.com/questions/5587482/hibernate-a-collection-with-cascade-all-delete-orphan-was-no-longer-referenc)? Main points: do not set list `myEnitities_` via setter, change it by using add/remove methods, and make sure that your equals/hashCode() methods are implemented correctly (hashCode may change if some of the fields changes) – Nowhere Man Apr 27 '20 at 21:03
  • @AlexRudenko Thanks for the help, but that wasn't the main cause. – whatamidoingwithmylife Apr 28 '20 at 08:32

1 Answers1

1

I fixed the issue, the cause was that I created new child entities and referenced parent entity in them, and right after that I would set the children of the parent entity using setter, which would cause previously persisted children entities to be dereferenced and cause the mentioned exception.

whatamidoingwithmylife
  • 1,119
  • 1
  • 16
  • 35