Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA's cascade = REMOVE and Hibernate's @OnDelete used together?

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?

like image 782
dexter meyers Avatar asked Dec 19 '11 15:12

dexter meyers


People also ask

What is the use of orphanRemoval?

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.

What is merge cascade type?

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.

What is CascadeType remove?

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.

What is Cascade all delete orphan in Hibernate?

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.


1 Answers

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

like image 55
Roger Keays Avatar answered Sep 19 '22 15:09

Roger Keays