My problem : How to evict 2nd level cached queries?
Technology used so far: Spring 3.2 framework with JPA 2.0 and hibernate 3.2.
I am having following properties defined in my persistence.xml:
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
So far we don't have a direct dependency on Hibernate anywhere in our code other than this.
query.setHint("org.hibernate.cacheable", true);
Coming back to the problem:
I have implemented 2nd level Query caching for a complex query( 6-7 table joins and some conditions).
The good thing is that data in all these tables are less likely to change and since same data is getting fired for each user,this is the perfect query to be cached.
However, if data in any one of the underlying tables gets updated, the cache needs to be evicted. JPA EntityManagerProvider provides two methods
emf.getCache().evictAll();
emf.getCache().evict();
I cann't use evictAll() as I believe it will clear all the cache for the application.
And evict() seems to be used for only evicting the cache from particular Entity not Queries.
So please provide me an optimum solution.
I need to do this when I using Entities that wrap database views. I used to never cache the view results, until I figured this out.
Here's what I do now:
When executing my query, I set a hint to both cache, and use a named cache region. The name is arbitrary and can be anything you want.
List allItems = em.createQuery("from EventStatus", EventStatus.class)
.setHint("org.hibernate.cacheable", true)
.setHint("org.hibernate.cacheRegion", "event-status")
.getResultList();
After modifying any entity that affects the query:
entityManagerFactory.unwrap(SessionFactory.class).getCache().evictQueryRegion("event-status");
I register a global listener in my configuration, and call evictQueryRegion after any relevant entity class has changed.
After any bulk delete (that fires no listener events), I manually evict the query cache region.
Of course, this is Hibernate specific.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With