Home > database >  Is the Hibernate first-level cache only synchronized one-way?
Is the Hibernate first-level cache only synchronized one-way?

Time:08-16

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.

There are other issues here that reference this topic: Hibernate first level cache - does it Sync? and Hibernate criteria.list() and Session refresh which are pretty old as of now.

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. But in other session, we got the updated value.

Am I missing the place where this is documented in the official documentation: Official documentation (or even as javadoc)?

CodePudding user response:

In short, yes, it is usually only synchronized to the database. You can ask Hibernate to refresh data though, by calling entityManager.refresh(entity).

The reason is quite simple, performance. Think about it, how can you make sure that the memory state is "current"? You would have to constantly query the database and ask for the current state, because databases usually have no concept of change notification. 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?

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.

  • Related