views:

857

answers:

1

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

+1  A: 

Hi,

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,

Arthur Ronald F D Garcia
Using @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) instead of @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) allowed EHCache to not invalidate after an entity was updated. I'm not sure what the performance penalties are with using READ_WRITE versus NONSTRICT_READ_WRITE. Also we are to far along in the project to fully enable optimistic locking using version column and timestamps, but that also seems like a good solution.
Dougnukem
Thanks, Take care of performances issues when using cache capabilities. Tomorrow, i will give you an additional insight about it.
Arthur Ronald F D Garcia