问题描述
我有一些由Hibernate管理的表,具有各种外键约束。级联删除目前仅由Hibernate管理。为了玩弄测试数据,我经常手动创建和删除一些行。如果我可以将ON DELETE CASCADE添加到外键约束中,它会帮助我很多,但我不知道Hibernate是否会因此而绊倒这个数据库,因为数据库在Hibernate之前将其删除。
很多人似乎都专注于DDL。我的意图是 not 指示Hibernate使用SQL DELETE CASCADES创建DDL。我只想知道,如果我在数据库中另外指定ON DELETE CASCADE以使JPA的 cascade = CascadeType.REMOVE
在引用注释中,例如 @ManyToOne
。
使用 CascadeType.DELETE
,但是这个注解只适用于 EntityManager
中的对象,而不是数据库。您要确保将 ON DELETE CASCADE
添加到数据库约束中。要验证,您可以配置JPA生成一个ddl文件。看看 ddl
文件,你会注意到 ON DELETE CASCADE
不是约束的一部分。将 ON DELETE CASCADE
添加到 ddl
文件中的实际SQL,然后从ddl更新数据库模式。这将解决您的问题。
显示了如何在 CONSTRAINT $ c $上使用
ON DELETE CASCADE
在MySQL中。你在约束上做到这一点。您还可以在 CREATE TABLE
或 ALTER TABLE
语句中执行此操作。 JPA很可能在 ALTER TABLE
语句中创建约束。只需在该语句中添加 ON DELETE CASCADE
即可。
Hibernate确实使用 @OnDelete
注释来提供这个功能,所以最好使用这个或者直接更新ddl文件,如果你想坚持标准的JPA功能。
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
.
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.
这篇关于我可以将'ON DELETE CASCADE'添加到由Hibernate管理的表中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!