I am using 2nd level cache and query cache. May I know how to programmatically clear all caches ?
7 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).
-
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? – Vikas Sharma Feb 16 '17 at 14:55
-
1I 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. – Dino Feb 17 '17 at 10:13
-
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? – Vikas Sharma Feb 17 '17 at 10:38
-
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. https://docs.jboss.org/hibernate/orm/4.3/devguide/en-US/html/ch06.html#caching-strategies-list) – Dino Feb 17 '17 at 14:09
To clear the session cache use session.clear()
To clear the 2nd level cache use this code snippet

- 588,226
- 146
- 1,060
- 1,140
-
7For modern versions of Hibernate, it would be better to follow the @dino's answer. – King Midas Oct 23 '14 at 09:18
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.

- 4,916
- 7
- 30
- 24
@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.
}

- 1,498
- 1
- 13
- 22
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();
}

- 1,923
- 1
- 18
- 18
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

- 4,873
- 2
- 32
- 50
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);

- 1
- 4