我正试图在删除另一个@OneToOne
相关实体时(通过SQL(使用触发器来清除一些相关实体。假设我有一个Person
和一个OrgUnit
,它们都引用了一些Address
。该CCD_ 5被映射有CCD_ 6和相关的外键约束。
以下触发器编译得很好:
CREATE OR REPLACE TRIGGER ON_DELETE_PERSON
AFTER DELETE ON PERSON
FOR EACH ROW
BEGIN
DELETE FROM ADDRESS WHERE ID = :OLD.ADDRESS_ID;
END;
/
但每当我试图删除Person
时,就会抛出以下错误:
DELETE FROM PERSON WHERE ID = 21179
ORA-04091: table MY_SCHEMA.PERSON is mutating, trigger/function may not see it
ORA-06512: in "MY_SCHEMA.ON_DELETE_PERSON", row 2
ORA-04088: error during execution of trigger 'MY_SCHEMA.ON_DELETE_PERSON'
必须更改什么才能使此触发器工作
在Java代码中,我可以简单地使用CascadeStyle.DELETE
。。。但我想将该责任转移到数据库,以便为所有数据提供正确的CCD_ 9行为。
-- CASCADE DELETE on ORGUNIT deletion...
ALTER TABLE PERSON ADD CONSTRAINT PERSON_F01
FOREIGN KEY (ORGUNIT_ID) REFERENCES ORGUNIT (ID)
ON DELETE CASCADE ENABLE VALIDATE;
-- SET NULL on ADDRESS deletion...
ALTER TABLE PERSON ADD CONSTRAINT PERSON_F02
FOREIGN KEY (ADDRESS_ID) REFERENCES ADDRESS (ID)
ON DELETE SET NULL ENABLE VALIDATE;
因此,删除一个ORGUNIT
也会自动删除所有相关的PERSON
。。。但是CCD_ 12将保留在数据库中。上面的触发器就是用来处理这种情况的。
所以在几条评论之后,答案弹出:
带有ON DELETE SET NULL
的FK约束会激发回表并导致该异常。看起来我不能两者都有。。。
在这种情况下,我将去掉ON DELETE
定义并冒FK约束错误的风险。通过触发器级联删除对我来说有更高的值