I have inherited a code base on which nearly all relations have the following annotations:
@OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, mappedBy = "someThing")
@OnDelete(action = OnDeleteAction.CASCADE)
Now I'm having trouble understanding what @OnDelete
does in the first place. Hibernate: OnDelete vs cascade=CascadeType.REMOVE is interesting, but unfortunately doesn't have any answers and the JavaDoc for @OnDelete
is particularly worthless.
From the other questions it looks like the OnDelete annotation somehow lets the DB do the cascading, while the cascading directive on @OneToMany
let's the ORM do it, but what would ever be the purpose of using them together?
And does @OneToMany
's cascade directive really doesn't allow the ORM implementation to generate a DB based cascade anyway?
As stated earlier, its usage is to delete orphaned entities from the database. An entity that is no longer attached to its parent is the definition of being an orphan.
CascadeType. MERGE. The merge operation copies the state of the given object onto the persistent object with the same identifier. CascadeType. MERGE propagates the merge operation from a parent to a child entity.
CascadeType. REMOVE : It means that the related entities are deleted when the owning entity is deleted. CascadeType. DETACH : It detaches all the related entities if a manual detach occurs.
all-delete-orphan - when an object is save/update/delete, check the associations and save/update/delete all the objects found. In additional to that, when an object is removed from the association and not associated with another object (orphaned), also delete it.
Let's say you have a one-to-one directional relationship
class House {
@OneToOne
Object door;
}
If you use CascadeType.REMOVE then deleting the house will also delete the door.
@OneToOne(cascade=CascadeType.REMOVE)
Object door;
If you use @OnDelete then deleting the door will also delete the house.
@OneToOne
@OnDelete(action = OnDeleteAction.CASCADE)
Object door;
Read more here: https://rogerkeays.com/jpa-cascadetype-remove-vs-hibernate-ondelete
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With