JPA: unidirectional many-to-one and cascading delete
Relationships in JPA are always unidirectional, unless you associate the parent with the child in both directions. Cascading REMOVE operations from the parent to the child will require a relation from the parent to the child (not just the opposite).
You'll therefore need to do this:
- Either, change the unidirectional
@ManyToOne
relationship to a bi-directional@ManyToOne
, or a unidirectional@OneToMany
. You can then cascade REMOVE operations so thatEntityManager.remove
will remove the parent and the children. You can also specifyorphanRemoval
as true, to delete any orphaned children when the child entity in the parent collection is set to null, i.e. remove the child when it is not present in any parent's collection. - Or, specify the foreign key constraint in the child table as
ON DELETE CASCADE
. You'll need to invokeEntityManager.clear()
after callingEntityManager.remove(parent)
as the persistence context needs to be refreshed - the child entities are not supposed to exist in the persistence context after they've been deleted in the database.
Unidirectional @OnetoMany mapping deletes all relationships and re-adds remaining ones rather than removing the specific one
Not sure if this is due to bag semantics(because you use a List
rather than Set
for reviews) or just because Hibernate sometimes does so called "collection recreations". Try using a Set
.
Hibernate unidirectional many-to-one and cascading delete
You can use SQL ON DELETE CASCADE
, but you have to be careful to evict all Child entities belonging to the Parent you are about to delete.
If you already loaded a Parent's Child, when you delete the Parent, the Child will be deleted from the database without Hibernate knowing about the entity state change.
To address this situation, it's better to evict all associated Child entities, to make sure you don't accidentally re-persist them through some other associations transitive persistence.
Related Topics
Should Private Helper Methods Be Static If They Can Be Static
How to Convert a String to Another Locale
How to Manage Exceptions Thrown in Filters in Spring
Code for Changing the Color of Subtasks in Gantt Chart
How to Change the Dock Icon of a Java Program
Create a New Line in Java's Filewriter
How to Make Notepad to Save Text in Utf-8 Without the Bom
Managing Constructors with Many Parameters in Java
Mockito: Trying to Spy on Method Is Calling the Original Method
Using Jasperreports with a Relative Path
Date Format Parse Exception - "Eee Mmm Dd Hh:Mm:Ss Z Yyyy"
How to Create a Stream from an Array
Java Date - Insert into Database
MAC Osx - Illegalstateexception: the Driver Is Not Executable: