Does Hibernate provide a way to invalidate L2 cache


#1

Hi,

I am using Hibernate L2 cache in my project and using EHCache as the caching provider. Hibernate version is 4.3.11 and EHCache 2.10.5.
The question I have is:
Hibernate will take care of updating the L2 cache when writes (inserts and updates) are done through Hibernate itself. Please correct me if I am wrong.

However when the database is updated through some other means, by some other application thus bypassing the Hibernate in my application, then Hibernate has no way to know that data has changed in the backend. In this case, the other application that updated the backend can send a notification to my application which can then use Hibernate API to invalidate the cache?

Or is there any other way to get around this?


#2

If the DB is changed outside of Hibernate, you can use a CDC (Change Data Capture) approach using a tool like the open-source Debezium project to extract changes and propagate them to Hibernate.

Or, you can run some introspection queries periodically to verify the modification timestamps of the underlying cached entities.

Or, you can just set the cached entries TTL to a lower values so that cached results are short-lived and they can be updated frequently via re-fetching from the DB.


#3

Thanks… yes, currently we are using 3rd approach that is using TTL of 1 hour.

The 2nd approach will require modification to the application.

The 1st approach, I could understand how Debezium would extract database changes however the later part, can you please elaborate more on ‘propagate them to Hibernate’. How will this happen since the hibernate is running inside my Java application process and Debezium would run in a different process I believe. How they will communicate?


#4

They will communicate via Kafka. Your application will have to read the Kafka log and make sure it updates the cache accordingly.

Check out this article, for more details about using Debezium, Kafka and Hibernate.


#5

If you are doing changes in Hibernate entities itself, you don’t have to do anything else to ensure the consistency of L2 cache, Hibernate will take care of it.

If you are doing changes via native queries, then explicitly mention which entities are affected, otherwise Hibernate will invalidate the entire second-level cache.

If you are changing data in the database from another process, then Hibernate is not aware of it, and you will have to define a strategy that best suits your requirements (expiration policies, explicit invalidation called from the outside of the application, etc).