强制Hibernate用ON DELETE CASCADE创建外键 [英] Force Hibernate to create foreign key with ON DELETE CASCADE

查看:393
本文介绍了强制Hibernate用ON DELETE CASCADE创建外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当Hibernate(或其他JPA实现)为@OneToMany关系创建外键时,是否有办法迫使它在数据库级别使用ON DELETE CASCADE?我发现,当我使用CascadeType.DELETE时,Hibernate不会在数据库级别执行此操作,而是发送两个删除语句(用于父级和子级记录)。或者,这可能是有原因的吗?

解决方案

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆