简体   繁体   中英

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 ?

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

To clear the session cache use session.clear()

To clear the 2nd level cache use this code snippet

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.

@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.
    }

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();
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM