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

17,082

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

Share:
17,082

Related videos on Youtube

dexter meyers
Author by

dexter meyers

Updated on June 04, 2022

Comments

  • dexter meyers
    dexter meyers about 2 years

    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?

  • Bruno
    Bruno over 8 years
    The behaviour with a @OneToOne and a @OneToMany doesn't seem to be quite the same. With @OneToMany(...) @OnDelete(action = OnDeleteAction.CASCADE) Object doors, it seems that deleting the house delete all its doors, but deleting a door doesn't delete the house.
  • Roger Keays
    Roger Keays over 8 years
    It would have to be @OneToMany List<Object> doors, I think. But besides that, this mapping wouldn't normally create a column on the House table. You'd either have a reverse mapping on Doors.house, or a collection table. For database cascading, I think the column has to be in the table you want to cascade into.
  • petertc
    petertc about 8 years
    Disagree. I think the the biggest difference between CascadeType.REMOVE and @OnDelete in user's view is that @OnDelete can work with JPAQL (since it is based on DB cascade), but CascadeType.REMOVE can not work with JPAQL.
  • Matthias
    Matthias almost 3 years
    '@OnDelete's purpose is to delegate the delete of related objects via the databases foreignkey contraints. You can achive the same by using @Cascade ragarding to your example