I have some tables managed by Hibernate with various foreign key constraints. Cascade on delete is currently managed by Hibernate alone. For playing around with test data I often create and remove some rows by hand. It would help me a lot if I could add ON DELETE CASCADE to the foreign key constraints but I don't know if Hibernate trips over this because the database removes stuff before Hibernate does.
A lot of people seem to concentrate on DDL. My intention is not to instruct Hibernate to create DDL with SQL DELETE CASCADES. I just want to know if it does any harm if I specify an ON DELETE CASCADE in the database in addition to having JPA's cascade = CascadeType.REMOVE
on the reference annotation, e.g., @ManyToOne
.
Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.
A special cascade style, delete-orphan, applies only to one-to-many associations, and indicates that the delete() operation should be applied to any child object that is removed from the association.
You can use CascadeType.DELETE
, however this annotation only applies to the objects in the EntityManager
, not the database. You want to be sure that ON DELETE CASCADE
is added to the database constraint. To verify, you can configure JPA to generate a ddl file. Take a look at the ddl
file, you'll notice that ON DELETE CASCADE
is not part of the constraint. Add ON DELETE CASCADE
to actual SQL in the ddl
file, then update your database schema from the ddl. This will fix your problem .
This link shows how to use ON DELETE CASCADE
on for CONSTRAINT
in MySQL. You do this on the constraint. You can also do it in a CREATE TABLE
or ALTER TABLE
statement. It's likely that JPA creates the constraint in an ALTER TABLE
statement. Simply add ON DELETE CASCADE
to that statement.
Note that some JPA implementors do provide a means for this functionality.
Hibernate does supply this functionality using the @OnDelete
annotation, thus it is preferred to use this or simply update the ddl file if you would like to stick with standard JPA functionality.
I see two potential issues:
Probably there are some other situations that could be problematic in some scenarios, so I would recommend not to do it.
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