Can I add 'ON DELETE CASCADE' to tables managed by Hibernate?

后端 未结 6 1735
不知归路
不知归路 2021-01-04 00:14

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

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 00:57

    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.

提交回复
热议问题