简体   繁体   English

Hibernate一级缓存是否只能单向同步?

[英]Is the Hibernate first-level cache only synchronized one-way?

Hibernate only synchronizes its first-level cache one-way by pushing its state to the database and it never synchronizes it the other way... or so I find empirically, because I was unable to find official documentation stating this. Hibernate 仅通过将其 state 推送到数据库来单向同步其一级缓存,并且它永远不会以另一种方式同步它......或者我凭经验发现,因为我无法找到说明这一点的官方文档。

There are other issues here that reference this topic: Hibernate first level cache - does it Sync?这里还有其他问题可以参考这个主题: Hibernate 一级缓存 - 它是否同步? and Hibernate criteria.list() and Session refresh which are pretty old as of now.Hibernate criteria.list() 和 Session 刷新到现在已经很老了。

This very recent article also refers to exactly this behavior as part of:这篇最近的文章也将这种行为作为以下内容的一部分:

Hibernate first level cache can have old values, as you can see above that I have put my program to sleep for 10 seconds and in that time I updated the value [...] but it didn't get reflected in the same session. Hibernate 一级缓存可以有旧值,正如你在上面看到的,我已经让我的程序休眠了 10 秒,在那段时间我更新了值 [...] 但它没有反映在同一个 session 中。 But in other session, we got the updated value.但在其他 session 中,我们得到了更新的值。

Am I missing the place where this is documented in the official documentation: Official documentation (or even as javadoc)?我是否错过了官方文档中记录的地方:官方文档(甚至是 javadoc)?

In short, yes, it is usually only synchronized to the database.简而言之,是的,通常只同步到数据库。 You can ask Hibernate to refresh data though, by calling entityManager.refresh(entity) .您可以通过调用entityManager.refresh(entity)来要求 Hibernate 刷新数据。

The reason is quite simple, performance.原因很简单,性能。 Think about it, how can you make sure that the memory state is "current"?想一想,如何确定 memory state 是“当前”的? You would have to constantly query the database and ask for the current state, because databases usually have no concept of change notification.您将不得不不断地查询数据库并询问当前的 state,因为数据库通常没有更改通知的概念。 In fact, it's actually pretty much impossible to do this reliably, because data could change all the time and what should happen when you work with an object that just changes while you are operating on the data of it?事实上,要可靠地做到这一点实际上几乎是不可能的,因为数据可能一直在变化,当您使用 object 时会发生什么,而 object 在您对其数据进行操作时会发生变化?

To have the illusion of "current data" you will have to use database locking.要产生“当前数据”的错觉,您将不得不使用数据库锁定。 Either pessimistic or optimistic locking, through which you can make sure that the data won't change by some other transaction, while your transaction is working on the data.悲观或乐观锁定,通过它您可以确保数据不会被其他事务更改,而您的事务正在处理数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM