强制Hibernate用ON DELETE CASCADE创建外键 [英] Force Hibernate to create foreign key with ON DELETE CASCADE
问题描述
在hibernate中,可以使用
@OnDelete(action = OnDeleteAction.CASCADE)
<你的@OneToMany关系。这告诉hibernate为生成的外键设置ON DELETE CASCADE。
请注意,这是一个hibernate扩展,并没有在JPA标准中指定。
小心使用。当你让数据库级联删除,这些都发生在hibernate的控制之外,所以:
- 你的二级缓存可能会失去同步。
- 您不能在这些实体上使用删除侦听器。我认为您应该只使用这个如果你有一个大的集合和性能的考虑迫使你让数据库处理删除,而不是休眠。
When Hibernate (or another JPA implementation) creates foreign key for @OneToMany relationship, is there a way to force it to use ON DELETE CASCADE at the database level? I found that when I use CascadeType.DELETE, Hibernate doesn't do it at the database level, but sends two delete statements (for parent and child records) instead. Or maybe there's a good reason for that?
解决方案In hibernate, you can use
@OnDelete(action = OnDeleteAction.CASCADE)
on your @OneToMany relationship. This tells hibernate to set ON DELETE CASCADE for the generated foreign key.
Note that this is a hibernate extension and is not specified in the JPA standard.
Use this with caution. When you let database cascade the deletes, these happen outside the control of hibernate so:
- Your second-level cache might become out of sync.
- You cant use on delete listeners on those entities.
I think you should only use this if you have a large collection and performance consideration forces you to let database handles the delete instead of hibernate.
这篇关于强制Hibernate用ON DELETE CASCADE创建外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!