java - 如何从 JPA EntityManager 清除 Hibernate 缓存?

标签 java spring hibernate jpa caching

我有一个带有 Hibernate 为我缓存的实体的应用程序。效果很好,除了我现在必须清除缓存(由于异步数据更改)。查询缓存如下:

query.setHint(QueryHints.HINT_CACHEABLE, true);
query.setHint(QueryHints.HINT_CACHE_REGION, "CACHE_REGION_NAME");

这些实体有适当的注释(据我所知):

@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "CACHE_REGION_NAME")

到目前为止一切顺利。现在我需要清除缓存。我执行以下操作:

@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);
    }
}

session 缓存没有问题,但我在尝试从 EntityManager 中解开 SessionFactory 时遇到异常:

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

我的 JPA bean 在 Spring 中配置如下:

<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>

<bean id="xproductEntityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="xproduct"/>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.cache.use_query_cache">true</prop>
            <prop key="hibernate.cache.use_second_level_cache">true</prop>
            <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
            <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
            <prop key="hibernate.generate_statistics">true</prop>
        </props>
    </property>
    <property name="jpaDialect" ref="jpaDialect" />
</bean>

<bean id="xProdTransaction" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="xproductEntityManagerFactory"/>
</bean>

有什么想法吗?

谢谢!

最佳答案

您无法直接使用 unwrap 获取每个类。您可以先获取 Session,然后从中获取 SessionFactory:

em.unwrap(Session.class).getSessionFactory();

关于java - 如何从 JPA EntityManager 清除 Hibernate 缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236118/

相关文章:

java - HQL:当其中一个字段是一对多列表时,如何查询某些字段?

Java、PowerMock——基于HttpPost请求体的模拟响应

xml - 元素 "context"的前缀 "context:component-scan"未绑定(bind)

java - 使用@PathVariable将参数传递给Spring Controller

java - Hibernate 中使用 ECache 的查询缓存的默认并发策略

java - hibernate 标准 API : get n random rows

java - 为什么我的方法会覆盖数组中的位置

java - 尝试将 Intent 转移到另一个适配器时应用程序崩溃

java - 在 itext 7 中将 html 转换为 pdf 时如何仅获得某些页面的横向方向?

spring - 如何使用 Spring Cloud Task 动态部署独立 Spring 批处理