且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除子级后,JPA关系未更新

更新时间:2022-12-03 22:54:30

JPA不会为您维护关系,应用程序必须维护它们。这意味着,无论何时删除实体,应用程序都有责任清理对该实体的所有引用。当它是外键关系时很明显,因为如果不这样做,数据库约束通常将导致异常。在反向引用的情况下,尽管关系没有严格的数据库约束,但用户通常会错误地认为JPA会处理它-导致缓存损坏。

JPA does not do relationship maintenence for you, the application must maintain them. That means when ever you delete an entity, the application is responsible for cleaning up any references to that entity. It is obvious when it is a foreign key relationship, as database constraints will usually cause an exception if it is not done. In the case of back references though where the relationship does not have a strict database constraint, users generally mistakenly believe that JPA will handle it - leaving the cache corrupted.

处理该问题的方法是删除对C和B实体的任何引用。在您的对象模型中,这意味着修复A的bList以删除B。我已经看到这是通过实体删除事件或在应用程序代码中处理的。由于在这种情况下,A没有外键,因此您也可以在删除发生后(即在刷新或提交之后)从数据库刷新受影响的A实体。

The way to handle it is to remove any references to C and B entities. In your object model, that means fixing A's bList to remove Bs. I have seen this handled through entity remove events or in application code. Since in this case, A does not have a foreign key, you could also refresh the affected A entities from the database after the delete has occured (ie after a flush or commit).