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

前端 未结 7 1401
长情又很酷
长情又很酷 2020-12-14 01:44

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

7条回答
  •  遥遥无期
    2020-12-14 02:29

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

提交回复
热议问题