ALTER TABLE添加ON DELETE CASCADE语句 [英] ALTER TABLE to add ON DELETE CASCADE statement
问题描述
我想在PostgreSQL中执行以下操作(使用Hibernate):
ALTER TABLE果实ADD CONSTRAINTS id ON DELETE CASCADE;
显然,我上面的代码不工作,所以我在寻找正确的语句。
如果我不能这样做,那么以下情况如何:
我的表中有一堆数据水果
。 fruits
中的 id
字段被表 grapes $ c用作外键$ C>。我需要删除
fruits
中的特定行,并且希望删除级联到 grapes
,并删除葡萄
,它具有指定的 id
。如何做到这一点?
从水果中删除其中id = 1级联;
注意:我不想进行连接并删除<$ c $中的相应数据C>葡萄。这只是一个例子。在实际的应用程序中,大量的表依赖于 fruits 。
因为我使用Hibernate,当我使用delete语句时,hibernate可以帮忙吗?
或者我可以用PostgreSQL中的信息模式或系统目录来做到这一点吗?
我找到了答案:
//在Fruit对象中
@OneToMany (mappedBy =fruit,orphanRemoval = true)
private List< Grape>葡萄;
//在Grape对象中
@OneToOne
私有水果;
I want to do the following in PostgreSQL (using Hibernate):
ALTER TABLE fruits ADD CONSTRAINTS id ON DELETE CASCADE;
Obviously, my code above is not working, so I am looking for the correct statement.
If I can't do that, then how about the following:
I have a bunch of data in my table fruits
. The id
field in fruits
is used as a foreign key by table grapes
. I need to delete a specific row in fruits
and I want the deletion to cascade to grapes
and delete all entries in grapes
that has the specified id
. How do I do that?
delete from fruits where id = 1 cascade;
NOTE: I don't want to do a join and delete the corresponding data in grape
. This is just an example. In the real application a large number of tables depend on fruits
.
Since I am using Hibernate, for the case when I use a delete statement, can hibernate help do it?
Or can I do this with the information schema or system catalog in PostgreSQL?
I found the answer:
//in Fruit object
@OneToMany(mappedBy = "fruit", orphanRemoval=true)
private List<Grape> grapes;
//in Grape object
@OneToOne
private Fruit fruit;
这篇关于ALTER TABLE添加ON DELETE CASCADE语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!