我使用hibernate作为我的对象关系管理解决方案,使用EHCache作为二级(读写)缓存。
我的问题是:是否可以直接访问二级缓存?
我想访问这个:http://www.hibernate.org/hib_docs/v3/api/org/hibernate/cache/ReadWriteCache.html
如何访问Hibernate正在使用的同一个ReadWriteCache?
我正在做一些直接/自定义的JDBC插入,我想自己将这些对象添加到二级缓存中。
发布于 2009-04-01 03:02:02
我会在映射到实体的EntityPersister上调用"afterInsert“,因为读/写是一种异步并发策略。我是在看了Hibernate 3.3源代码之后拼凑起来的。我不是100%,这将工作,但它看起来很好。
EntityPersister persister = ((SessionFactoryImpl) session.getSessionFactory()).getEntityPersister("theNameOfYourEntity");
if (persister.hasCache() &&
!persister.isCacheInvalidationRequired() &&
session.getCacheMode().isPutEnabled()) {
CacheKey ck = new CacheKey(
theEntityToBeCached.getId(),
persister.getIdentifierType(),
persister.getRootEntityName(),
session.getEntityMode(),
session.getFactory()
);
persister.getCacheAccessStrategy().afterInsert(ck, theEntityToBeCached, null);
}--
/**
* Called after an item has been inserted (after the transaction completes),
* instead of calling release().
* This method is used by "asynchronous" concurrency strategies.
*
* @param key The item key
* @param value The item
* @param version The item's version value
* @return Were the contents of the cache actual changed by this operation?
* @throws CacheException Propogated from underlying {@link org.hibernate.cache.Region}
*/
public boolean afterInsert(Object key, Object value, Object version) throws CacheException;发布于 2009-04-01 03:40:25
我通过创建自己的缓存提供程序来做到这一点。我只是重写了EhCacheProvider,并为管理器使用了我自己的变量,这样我就可以在一个静态变量中返回它。一旦获得CacheManager,就可以调用manager.getCache(class_name)来获得该实体类型的缓存。然后使用主键、类型和类名构建一个CacheKey:
CacheKey cacheKey = new CacheKey(key, type, class_name, EntityMode.POJO,
(SessionFactoryImplementor)session.getSessionFactory());缓存本质上是一个映射,因此您可以检查对象是否在缓存中,或者遍历实体。
在最初构建SessionFactory时,可能有一种方法可以访问CacheProvider,这样就不需要实现自己的SessionFactory了。
发布于 2012-05-15 17:03:50
hibernate和JPA现在都提供了对底层二级缓存的直接访问:
sessionFactory.getCache();
entityManager.getCache();https://stackoverflow.com/questions/702175
复制相似问题