membersound
membersound

Reputation: 86747

Is ON DELETE CASCADE on a child entity correct?

I have a parent-child relation, and I want hibernate to autogenerate the schema. Especially the database trigger ON DELETE CASCADE should be set property.

Means: when I delete the parent, the child should of course be removed. But when I remove a child, the parent should remain.

@Entity
public class MyOffer {
    @OneToMany(mappedBy = "offer", cascade.CascadeType.ALL, orphanRemoval = true)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Set<MyCategory> categories;
}

@Entity
public class MyCategory {
        @ManyToOne
        private MyOffer offer;
}

This creates the following schema:

CREATE TABLE my_category(
...
CONSTRAINT fk_offer FOREIGN KEY (fk_offer_id)
      REFERENCES offers (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)

Question: is that correct, that the cascade is created an active on the child, and not at the parent?

Upvotes: 0

Views: 188

Answers (1)

Dean Clark
Dean Clark

Reputation: 3868

Yes, it's a property of the Foreign Key constraint.

That said, if you ever do this with any sort of volume, you'll want to make sure the FK on the child table is indexed. Otherwise any delete from the parent table will cause a full table scan of the child table, regardless of whether or not there is a child row to delete.

Upvotes: 1

Related Questions