title: How do I clear a Hibernate cache from a JPA EntityManager?
body: <p>I have an application with entities which Hibernate is caching for me.  Works great except that I now I have to clear the cache (due to asynchronous data changes).  Queries are cached as follows:</p>
  
  <pre><code>query.setHint(QueryHints.HINT_CACHEABLE, true);
  query.setHint(QueryHints.HINT_CACHE_REGION, "CACHE_REGION_NAME");
  </code></pre>
  
  <p>The entities have the appropriate annotations (as far as I can tell):</p>
  
  <pre><code>@Cacheable
  @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "CACHE_REGION_NAME")
  </code></pre>
  
  <p>So far so good.  Now I need to clear the cache.  I do the following:</p>
  
  <pre><code>@Override
  @Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW, value = "xProdTransaction")
  public void clearClientCache() throws CacheClearingException {
      clearSession();
      clearCacheRegion();
  }
  
  void clearSession() throws CacheClearingException {
      Session session = null;
      try {
          session = em.unwrap(Session.class);
  
          if(session==null) {
              throw new CacheClearingException("Unable to find valid session");
          } else {
              session.clear();
          }
      } catch(PersistenceException pe) {
          throw new CacheClearingException("Unable to clear session", pe);
      }
  }
  
  void clearCache() throws CacheClearingException {
      Cache cache = null;
      try {
          SessionFactory sessionFactory = em.unwrap(SessionFactory.class);
          if(sessionFactory == null) {
              throw new CacheClearingException("Unable to find valid session factory");
          }
  
          cache = sessionFactory.getCache();
          if (cache == null) {
              throw new CacheClearingException("Unable to find valid cache");
          }
  
          cache.evictCollectionRegion("CACHE_REGION_NAME");
      } catch (PersistenceException pe) {
          throw new CacheClearingException("Unable to clear cache", pe);
      }
  }
  </code></pre>
  
  <p>The session cache is no problem, but I get an exception attempting to unwrap the SessionFactory from the EntityManager:</p>
  
  <pre><code>com.cambia.shc.core.dao.xproduct.CacheClearingException: Unable to clear cache
      at com.cambia.shc.core.dao.xproduct.CacheManagerImpl.clearCache(CacheManagerImpl.java:63)
      at com.cambia.shc.core.dao.xproduct.CacheManagerImpl.clearClientCache(CacheManagerImpl.java:29)
  ...
  Caused by: javax.persistence.PersistenceException: Hibernate cannot unwrap interface org.hibernate.SessionFactory
      at org.hibernate.jpa.spi.AbstractEntityManagerImpl.unwrap(AbstractEntityManagerImpl.java:1524)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:606)
      at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:291)
      at com.sun.proxy.$Proxy66.unwrap(Unknown Source)
      at      com.cambia.shc.core.dao.xproduct.CacheManagerImpl.clearCache(CacheManagerImpl.java:51)
      ... 94 more
  </code></pre>
  
  <p>My JPA beans are configured in Spring as follows:</p>
  
  <pre><code>&lt;bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/&gt;
  
  &lt;bean id="xproductEntityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"&gt;
      &lt;property name="persistenceUnitName" value="xproduct"/&gt;
      &lt;property name="jpaProperties"&gt;
          &lt;props&gt;
              &lt;prop key="hibernate.cache.use_query_cache"&gt;true&lt;/prop&gt;
              &lt;prop key="hibernate.cache.use_second_level_cache"&gt;true&lt;/prop&gt;
              &lt;prop key="hibernate.cache.provider_class"&gt;org.hibernate.cache.EhCacheProvider&lt;/prop&gt;
              &lt;prop key="hibernate.cache.region.factory_class"&gt;org.hibernate.cache.ehcache.EhCacheRegionFactory&lt;/prop&gt;
              &lt;prop key="hibernate.generate_statistics"&gt;true&lt;/prop&gt;
          &lt;/props&gt;
      &lt;/property&gt;
      &lt;property name="jpaDialect" ref="jpaDialect" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="xProdTransaction" class="org.springframework.orm.jpa.JpaTransactionManager"&gt;
      &lt;property name="entityManagerFactory" ref="xproductEntityManagerFactory"/&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>Any ideas?</p>
  
  <p>Thanks!</p>