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"
Standort Hannover
newcubator GmbH
Bödekerstraße 22
30161 Hannover
Standort Dortmund
newcubator GmbH
Westenhellweg 85-89
44137 Dortmund