Sunday, October 18, 2020

Grails on Groovy - Clear and Flush Current Hibernate Session Data and Evict All Query Cache Data | Clearing Hibernate Query Cache in Grails

Hibernate already has support for query cache. And we know that when we perform a big task there are huge number queries remain in our cache factory. And more important that in most cases we don't need this caches so as a result cache factory getting full with unusual cache data.
This could be a performance issue - so it's better we clear cache on our own responsibility after a big task completed.
Below are the procedure to flush and clear current session (hibernate session) data so that cache factory have enough space for further execution.
import org.hibernate.SessionFactory
import grails.util.Holders

private static SessionFactory _sessionFactory

static Boolean flushAndClearCache() {
    try {
        sessionFactory.currentSession.flush()
        sessionFactory.currentSession.clear()
        sessionFactory.getCache().evictEntityRegions()
        sessionFactory.getCache().evictCollectionRegions()
        sessionFactory.getCache().evictDefaultQueryRegion()
        sessionFactory.getCache().evictQueryRegions()
        return true
    }
    catch (Throwable ex) {
        log.error(ex.ex)
        return false
    }
}

static <T> T getBean(Class<T> requiredType) {
    try {
        return Holders.applicationContext.getBean(requiredType)
    }
    catch (Throwable e) {
        return null
    }
}

static SessionFactory getSessionFactory() {
    _sessionFactory = _sessionFactory ?: (_sessionFactory = getBean(SessionFactory))
}