[英]Manipulating Hibernate 2nd Level Cache
我使用 hibernate 作为我的 ORM 解决方案,使用 EHCache 作为二级(读写)缓存。
我的问题是:是否可以直接访问二级缓存?
我想访问这个: http://www.hibernate.org/hib_docs/v3/api/org/hibernate/cache/ReadWriteCache.html
如何访问 Hibernate 使用的同一个 ReadWriteCache?
我有一些我正在做的直接/自定义 JDBC 插入,我想自己将这些对象添加到二级缓存中。
我会在映射到您的实体的 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;
hibernate 和 JPA 现在都提供对底层二级缓存的直接访问:
sessionFactory.getCache();
entityManager.getCache();
我通过创建自己的缓存提供程序来做到这一点。 我只是覆盖了 EhCacheProvider 并将我自己的变量用于管理器,因此我可以在 static 中返回它。 获取 CacheManager 后,您可以调用 manager.getCache(class_name) 来获取该实体类型的 Cache。 然后使用主键、类型和 class 名称构建一个 CacheKey:
CacheKey cacheKey = new CacheKey(key, type, class_name, EntityMode.POJO,
(SessionFactoryImplementor)session.getSessionFactory());
缓存本质上是一个 map,因此您可以检查您的 object 是否在缓存中,或者遍历实体。
当您最初构建 SessionFactory 时,可能有一种访问 CacheProvider 的方法,这将避免您自己实现的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.