在数据库模式中Hibernate二级缓存和ON DELETE CASCADE [英] Hibernate second level cache and ON DELETE CASCADE in database schema
问题描述
在我们的数据库中指定 FOREIGN KEY
约束架构。我们的大部分 FOREIGN KEY
约束条件也指定 ON DELETE CASCADE
。
自从我们启用第二个级别后,性能有所提高缓存。但是我们也开始遇到ObjectNotFoundExceptions。
看起来ObjectNotFoundExceptions正在发生,因为数据库正在删除 下面的表格行 Hibernate。例如,当我们用Hibernate删除 Parent
时,数据库模式将 ON DELETE CASCADE
添加到任何子
实体。这显然没有休眠知识,所以它没有机会更新二级缓存(并删除任何已删除的 Child
实体)。
我们相信解决这个问题的方法是从我们的数据库模式中删除 ON DELETE CASCADE
(但保留 FOREIGN KEY
S)。相反,我们需要配置Hibernate使用普通的删除SQL来删除 Child
依赖项,这也将使Hibernate更新第二级缓存。一些有限的测试表明,这种方法似乎工作。
我想得到一些社区反馈。我们的问题是否有其他更好的解决方案?别人如何处理这种情况?一般来说,在使用Hibernate的数据库模式中使用 ON DELETE CASCADE
应该考虑什么?
感谢。
如果您总是要通过程序删除, hibernate对象ON DELETE CASCADE来照顾相关的人。另一方面,如果你打算在java应用程序中删除对象,有时候在您的数据库级别,最终会出现奇怪的挂起数据。在这种情况下,您可能需要研究一个更复杂的方法。您不清楚是否是这种情况,所以不要在这里详细介绍。
Our Java application has about 100 classes mapped to a database (SQL Server or MySQL). We are using Hibernate as our ORM (with XML mapping files).
We specify FOREIGN KEY
constraints in our database schema. Most of our FOREIGN KEY
constraints also specify ON DELETE CASCADE
.
We've recently started enabling Hibernate 2nd level caching (for popular entities and collections) to mitigate some performance problems.
Performance has improved since we enabled the 2nd level cache. However we've also started encountering ObjectNotFoundExceptions.
It seems the ObjectNotFoundExceptions are occuring because the database is deleting table rows underneath Hibernate. For example, when we delete a Parent
with Hibernate, the database schema will ON DELETE CASCADE
to any Child
entities. This obviously happens without Hibernates knowledge, so it doesn't get a chance to update the 2nd level cache (and remove any deleted Child
entities).
We believe the solution to this problem is to remove ON DELETE CASCADE
from our database schema (but keep the FOREIGN KEY
s). Instead, we need to configure Hibernate to delete Child
dependencies with normal delete SQL which will also make Hibernate update the 2nd level cache. Some limited testing has shown that this approach seems to work.
I wanted to get some community feedback on this. Are there alternative (better?) solutions to our problem? How do others handle this situation? In general, what are the tradeoffs that should be considered when using ON DELETE CASCADE
in a database schema with Hibernate?
Thanks.
If you are always going to delete through your program, you want to take the constraint off the database and tell the hibernate object to ON DELETE CASCADE to take care of the related guys.
On the other hand, if you are going to delete objects sometimes in your java app, and sometimes at your database level, you will end up with weird hanging data. In this case you may need to look into a more complicated approach.. You weren't clear if this was the case, so not going to go into more detail here.
这篇关于在数据库模式中Hibernate二级缓存和ON DELETE CASCADE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!