cometta
cometta

Reputation: 35689

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

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

Upvotes: 31

Views: 70770

Answers (8)

JayDesAt
JayDesAt

Reputation: 37

Using Spring, the only solution working for me was different than all the other ones, but really simple. Using the Spring Cache manager, otherwise all the cached Spring queries will stay cached:

import org.springframework.cache.CacheManager;

@Autowired
CacheManager cacheManager;

void clearCache() {
  for (var cacheName : cacheManager.getCacheNames()) {
    Objects.requireNonNull(cacheManager.getCache(cacheName)).clear();
  }
}

Upvotes: 1

Thanh Nguyen Van
Thanh Nguyen Van

Reputation: 1983

Same as @Dino's answer, shortened syntax for JPA 2.0 API:

@Autowired
private EntityManagerFactory entityManagerFactory;

public void clearHibernateCaches() {
    entityManagerFactory.getCache().unwrap(org.hibernate.Cache.class).evictAllRegions();
}

Upvotes: 1

KC Baltz
KC Baltz

Reputation: 1508

@Dino 's answer almost worked for me but I got an error from sessionFactory.getCurrentSession() (No currentSessionContext configured!). I found this worked for me:

    // Use @Autowired EntityManager em
    em.getEntityManagerFactory().getCache().evictAll();

    // All of the following require org.hibernate imports
    Session session = em.unwrap(Session.class);

    if (session != null) {
        session.clear(); // internal cache clear
    }

    SessionFactory sessionFactory = em.getEntityManagerFactory().unwrap(SessionFactory.class);

    Cache cache = sessionFactory.getCache();

    if (cache != null) {
        cache.evictAllRegions(); // Evict data from all query regions.
    }

Upvotes: 2

atish shimpi
atish shimpi

Reputation: 5023

If you want to clear 2nd level cache, use api sessionFactory.evictEntity(entityName)

Code:

/**
 * Evicts all second level cache hibernate entites. This is generally only
 * needed when an external application modifies the database.
 */
public void evict2ndLevelCache() {
    try {
        Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata();
        for (String entityName : classesMetadata.keySet()) {
            logger.info("Evicting Entity from 2nd level cache: " + entityName);
            sessionFactory.evictEntity(entityName);
        }
    } catch (Exception e) {
        logger.logp(Level.SEVERE, "SessionController", "evict2ndLevelCache", "Error evicting 2nd level hibernate cache entities: ", e);
    }
}

For more details on 2nd level cache refer

Upvotes: 0

Dino
Dino

Reputation: 720

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).

Upvotes: 39

Raju Yadav
Raju Yadav

Reputation: 1

you can go with this also

request.getSession().invalidate();      
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); 
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

Upvotes: -13

Taylor Gautier
Taylor Gautier

Reputation: 4944

If you plug in Terracotta, you also have the ability to run the Terracotta Dev Console which can inspect statistics about the cache, turn on and turn off the cache, and clear the cache contents from the user interface.

This functionality is also available from JMX beans.

Upvotes: 3

Bozho
Bozho

Reputation: 597106

To clear the session cache use session.clear()

To clear the 2nd level cache use this code snippet

Upvotes: 17

Related Questions