Question

I'm wondering if it's possible for Hibernate second level cache (we're using EHCache) to allow an application to cache an Entity that has been comitted to the DB if it knows that no other applications are modifying the DB.

My thought is that if I update record A, then I know the value of record A and should be able to cache that, JVM clustering systems like Terracotta support this type of behavior in terms of JVM heap memory using Java synchronization locks.

EHCache lock mode configuration in Hibernate

Was it helpful?

Solution

State of the art POJO's in Action book talks about it

If a single-server application updates the database using the persistence framework, the framework updates the process-level cache.

And...

Cached objects that are updateable should typically use optimistic locking because that will prevent the application from blindly overwriting changes in the database. AND if a transaction updates a cached object that had already been changed in the database, the optimistic locking failure will cause the transaction to be rolled back. The persistence framework will remove the stale data from the cache, and the application can retry transaction with the latest version of the data.

And choose one of the following strategies according to JPA with Hibernate book

  • Transactional: available in a managed environment only, it guarantees full transactional isolation up to repeatable read, if required. Use this strategy for read-mostly data where it’s critical to prevent stale data in concurrent transactions, in the rare case of an update.
  • Read-write: This strategy maintains read committed isolation, using a timestamping mechanism and is available only in nonclustered environments. Again, use this strategy for read-mostly data where it’s critical to prevent stale data in concurrent transactions, in the rare case of an update.

Added to original anwser: Hibernate DOES NOT GUARANTEE consistency between the cache and the database whether you use @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE). If you want to use it, so you SHOULD configure a sufficiently short expiry timeout which can affect perfomance.

regards,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top