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

8

31

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

Cowgirl answered 17/3, 2010 at 9:31 Comment(0)
R
17

To clear the session cache use session.clear()

To clear the 2nd level cache use this code snippet

Radiotelephony answered 17/3, 2010 at 9:33 Comment(1)
For modern versions of Hibernate, it would be better to follow the @dino's answer.Returnee
M
39

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

Moniz answered 23/12, 2013 at 15:39 Comment(4)
I want to clear cache data from 2nd level cache by calling below method:- sessionFactory.getCache().evictEntityRegions(); I just want to know , is there any harm in doing this? For eg:- What will happen if i try to clear cache in middle of transaction?Indeed
I guess it depends of your caching strategy and provider. You may need to test it with the chosen one. The reference doc describes the different settings.Moniz
I am using @Cache(usage = CacheConcurrencyStrategy.READ_WRITE). I have a case.Suppose if some transaction is running to get Data from and 2nd level cache has data at that time. At the same time, another thread evicts all region caches while the previous transaction is not completed yet. Then what will happen in this case. Can i get null from cache in that transaction and a db hit will occur ? Is there any chance of any issue?Indeed
You should write a test with your specific context. According to documentation, the read-write seems to match your case but take note that it has requirements, all detailed here (cf. docs.jboss.org/hibernate/orm/4.3/devguide/en-US/html/…)Moniz
R
17

To clear the session cache use session.clear()

To clear the 2nd level cache use this code snippet

Radiotelephony answered 17/3, 2010 at 9:33 Comment(1)
For modern versions of Hibernate, it would be better to follow the @dino's answer.Returnee
S
3

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.

Shebashebang answered 17/3, 2010 at 20:10 Comment(0)
M
2

@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.
    }
Mariehamn answered 30/8, 2019 at 20:4 Comment(0)
B
1

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();
}
Bean answered 3/6, 2020 at 2:10 Comment(0)
I
1

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();
  }
}
Inclusion answered 3/6 at 9:27 Comment(0)
K
0

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

Kelwunn answered 26/10, 2015 at 6:56 Comment(0)
O
-13

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);
Orff answered 29/1, 2015 at 7:43 Comment(1)
HttpSession and hibernate session are different things.Sura

© 2022 - 2024 — McMap. All rights reserved.