Clear Hibernate 2nd level cache after manually DB update

As mentioned, when you update DB from the back-end manually (not though application/ hibernate session), the cache is not updated. And your application remains ignorant about it.

To tell the app about the change, you need to refresh the entire cache or part of the cache related to the entity depending on the case. This can be one in two ways:

1- Restart the application - In this case the cache will be rebuild with updated DB change.

2- Trigger the update w/o restarting the app - You need not restart the app but you want to tell you application that the current cache in invalid and it should be refreshed.

  • You can give this external push to you app in many ways. Few are listed below.

    1. Through JMX.
    2. Through a servlet with a published URL to refresh the cache. Hit the URL after you change tables in DB.
    3. Implementing a trigger on the database that call a listener on the application.
  • While implementing the external push/ admin task, you can call a suitable cache related method based on your requirement to invalidate cache/ refresh cache. Examples: Session.refresh(), Cache.evictAllRegions(), Cache.evictEntityRegion(entityName) etc as described in other posts.


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

evictAllRegions() Evict all data from the cache.

Using Session and SessionFactory:

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

1) If you need update only one entity (if directly from db you will update only certain entities) not whole session, you can use

evictEntityRegion(Class entityClass) Evicts all entity data from the given region (i.e.

2) If you have a lot of entities, that can be updated directly from db you can use this method that evicts all entities from 2nd level cache (we can expose this method to admins through JMX or other admin tools):

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

3) Another approach is described here for postgresql+hibernate, I think you can do something similar for Oracle like this


Use debezium for asynchronous cache updation from your database. You can know more by visiting https://debezium.io/

Also this article is very helpful as it gives direct implementation https://debezium.io/blog/2018/12/05/automating-cache-invalidation-with-change-data-capture/