我有一个Hibernate为我提供缓存的实体的应用程序。工作得很好,除了我现在必须清除缓存(由于异步数据更改)。查询缓存如下:
audioDemo.html:42 audio = [object HTMLAudioElement]
audioDemo.html:43 audio src = file:///C:/xampp/htdocs/enhzflep/audio/voice_welcomeback.mp3
audioDemo.html:44 audio dur = 1.68
audioDemo.html:42 audio = [object HTMLAudioElement]
audioDemo.html:43 audio src = file:///C:/xampp/htdocs/enhzflep/audio/Some%20Chords.mp3
audioDemo.html:44 audio dur = 444.186122
实体有适当的注释(据我所知):
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")
会话缓存没问题,但是我尝试从EntityManager中解包SessionFactory时遇到异常:
@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);
}
}
我的JPA bean在Spring中配置如下:
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
有什么想法吗?
谢谢!