当我删除一行时,如何自动从联接 table 中删除另一行?

How can I automatically delete another row from a join table when I delete a row?

我正在通过直接连接 table RelatedDocuments:

为 table Document 中的一行或多行之间的关系建模
-----------
|from| to |
-----------
|   1|   2|
|   1|   5|
|   7|   1|
-----------

但是,因为这些关系对于我的用例来说基本上是双向的(而且,考虑到这一点,为了便于通过 JPA 访问)我添加了一个触发器,"mirrors" 插入时 from 和 two 之间的每个关系。

-----------
|from| to |
-----------
|   1|   2|
|   2|   1|
|   1|   5|
|   5|   1|
|   7|   1|
|   1|   7|
-----------

这让我可以轻松找到所有 Document 相关的内容,例如ID 1. 但是,由于

,我无法实现相应的删除触发器("delete the opposite of what you just deleted")
ORA-04091: table RELATEDDOCUMENTS is mutating, trigger/function may not see it

,非常正确地表明我正在尝试操纵触发触发器的 table。有解决这个问题的好方法吗?特别是 wrp/ 对我来说想要利用普通的 JPA?

您可以在 compound trigger 中执行此类操作,但我认为最好的方法是调整删除语句。如果你想删除 (1,2) 关系,你会这样做:

delete from relateddocuments
  where ( from = 1 and to = 2 )
     or ( from = 2 and to = 1 );

这是编写存储过程来处理您的 SQL 真正有帮助的地方。