JPA Reference with "orphanRemoval"

Orphan Removal

JPA 2 supports an additional and more aggressive remove cascading mode which can be specified using the orphanRemoval element of the @onetoone and @onetomany annotations:

JPA will keep track of the referencing Objects which need to be removed, when its managed via an PersistentBag:

   @OneToMany(..., orphanRemoval = true)
   private List<Address> addresses = new ArrayList<>();
      
   ...

   employee = employeeRepository.findById(id);
   employee.getAddresses().clear() 

employee.getAdresses() is a hibernate.PersistenceBag therefore hibernate will track the changes within the collection and propagate those to the underlying database (like delete the addresses which have been referenced by the employee when orphanRemoval = true)

If we overwrite the Collection, hibernate is unable to tell what has changed and will fail e.g.

   employee = employeeRepository.findById(id);
   employee.setAddresses(findAddresses(employee))

The Error will be something like this when there were Addresses within the Collection

"A collection with cascade=\"all-delete-orphan\" was no longer referenced by the owning entity instance: xxx nested exception is org.hibernate.HibernateException: A collection with cascade=\"all-delete-orphan\" was no longer referenced by the owning entity instance: xxx"

Wir freuen uns Sie kennen zu lernen

Hat Sie unser Angebot überzeugt? Dann freuen wir uns, Sie kennen zu lernen. Kontaktieren Sie uns gerne für ein unverbindliches Erstgespräch.

newcubator GmbH
Freie-Vogel-Straße 369
44269 Dortmund
dortmund@newcubator.com
+49 231/586 873 80
newcubator GmbH
Bödekerstraße 22
30161 Hannover
hannover@newcubator.com
+49 511/957 313 00