Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear all Hibernate cache (ehcache) using Spring?

Tags:

I am using 2nd level cache and query cache. May I know how to programmatically clear all caches ?

like image 897
cometta Avatar asked Mar 17 '10 09:03

cometta


People also ask

How do I clear Hibernate cache in spring boot?

We can use session clear() method to clear the cache i.e delete all the objects from the cache. We can use session contains() method to check if an object is present in the hibernate cache or not, if the object is found in cache, it returns true or else it returns false.

How do you clear Ehcache in spring?

Spring provides two ways to evict a cache, either by using the @CacheEvict annotation on a method, or by auto-wiring the CacheManger and clearing it by calling the clear() method.

How do you clean an Ehcache?

ehcache. CacheManager which provide a clearAll() operation. Show activity on this post. And then connect to the java process using jconsole and use Mbean method invocation - to clear the second level cache!

Is Ehcache in memory cache?

1. Overview. In this article, we will introduce Ehcache, a widely used, open-source Java-based cache. It features memory and disk stores, listeners, cache loaders, RESTful and SOAP APIs and other very useful features.


2 Answers

The code snippet indicated in Bozho answer is deprecated in Hibernate 4.

According to Hibernate JavaDoc, you can use org.hibernate.Cache.evictAllRegions() :

Evict data from all query regions.

Using the API :

Session session = sessionFactory.getCurrentSession();  if (session != null) {     session.clear(); // internal cache clear }  Cache cache = sessionFactory.getCache();  if (cache != null) {     cache.evictAllRegions(); // Evict data from all query regions. } 

Alternatively, you can clear all data from a specific scope :

org.hibernate.Cache.evictCollectionRegions() org.hibernate.Cache.evictDefaultQueryRegion() org.hibernate.Cache.evictEntityRegions() org.hibernate.Cache.evictQueryRegions() org.hibernate.Cache.evictNaturalIdRegions() 

You might want to check the JavaDoc for hibernate Cache interface (Hibernate 4.3).

And also, second-level cache eviction from hibernate dev guide (4.3).

like image 74
Dino Avatar answered Sep 23 '22 15:09

Dino


To clear the session cache use session.clear()

To clear the 2nd level cache use this code snippet

like image 31
Bozho Avatar answered Sep 24 '22 15:09

Bozho