不幸的是,Oracle (至少我正在使用的版本)不支持自动级联删除。在删除父记录之前,必须分别删除子记录以避免违反约束?
当删除在@OneToMany上设置了CascadeType.DELETE的父对象时,Hibernate何时决定逐个删除每个子实例和批量删除外键。
例如,
父表:
PARENT_ID
1
2
儿童桌:
CHILD_ID PARENT_ID
1.商业、商业、金融、商业、金融等领域。
2
第三条
删除父级可以通过两种方式级联删除子级:
delete from CHILD where child_id = 1
delete from CHILD where child_id = 2
delete from PARENT where parent_id = 1或
delete from CHILD where parent_id = 1
delete from PARENT where parent_id = 1我见过Hibernate做这两种事。我不明白Hibernate是如何决定使用哪种策略的。看起来,如果集合实际上是初始化的,则很可能在前面的示例中执行单独的删除操作。但是,如果集合与会话中的内容不匹配,这很容易导致ConstraintViolationException错误。
发布于 2010-12-28 15:45:37
我不能回答你问题的冬眠部分。但你也提到:
“甲骨文(至少我正在使用的版本)不支持自动级联删除”
这就是我可以用一个例子来反驳的部分。
首先,设置具有主键约束的表:
SQL> create table parent (id)
2 as
3 select 1 from dual union all
4 select 2 from dual
5 /
Table created.
SQL> alter table parent
2 add constraint parent_pk
3 primary key (id)
4 /
Table altered.
SQL> create table child (id, parent_id)
2 as
3 select 1, 1 from dual union all
4 select 2, 1 from dual union all
5 select 3, 2 from dual
6 /
Table created.
SQL> alter table child
2 add constraint child_pk
3 primary key (id)
4 /
Table altered.您可能有一个正常的外键约束:
SQL> alter table child
2 add constraint child_parent_fk
3 foreign key (parent_id)
4 references parent(id)
5 /
Table altered.你可以看到级联删除不起作用:
SQL> delete parent
2 where id = 1
3 /
delete parent
*
ERROR at line 1:
ORA-02292: integrity constraint ([schema].CHILD_PARENT_FK) violated - child record found但是,如果使用ON DELETE CASCADE子句定义外键约束.
SQL> alter table child
2 drop constraint child_parent_fk
3 /
Table altered.
SQL> alter table child
2 add constraint child_parent_fk
3 foreign key (parent_id)
4 references parent(id)
5 on delete cascade
6 /
Table altered...。然后,当父记录被删除时,子记录会自动删除:
SQL> select * from parent
2 /
ID
----------
1
2
2 rows selected.
SQL> select * from child
2 /
ID PARENT_ID
---------- ----------
1 1
2 1
3 2
3 rows selected.
SQL> delete parent
2 where id = 1
3 /
1 row deleted.
SQL> select * from parent
2 /
ID
----------
2
1 row selected.
SQL> select * from child
2 /
ID PARENT_ID
---------- ----------
3 2
1 row selected.你好,罗伯。
https://stackoverflow.com/questions/4547006
复制相似问题