5

我使用休眠作为我的 ORM 解决方案,使用 EHCache 作为二级(读写)缓存。

我的问题是:是否可以直接访问二级缓存?

我想访问这个:http ://www.hibernate.org/hib_docs/v3/api/org/hibernate/cache/ReadWriteCache.html

如何访问 Hibernate 使用的同一个 ReadWriteCache?

我有一些我正在做的直接/自定义 JDBC 插入,我想自己将这些对象添加到二级缓存中。

4

3 回答 3

6

我会在映射到您的实体的 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-01T03:02:01.970 回答
1

我通过创建自己的缓存提供程序来做到这一点。我只是覆盖了 EhCacheProvider 并将我自己的变量用于管理器,因此我可以将它以静态形式返回。获取 CacheManager 后,您可以调用 manager.getCache(class_name) 来获取该实体类型的 Cache。然后使用主键、类型和类名构建一个 CacheKey:

  CacheKey cacheKey = new CacheKey(key, type, class_name, EntityMode.POJO,
    (SessionFactoryImplementor)session.getSessionFactory());

缓存本质上是一个地图,因此您可以检查您的对象是否在缓存中,或者遍历实体。

当您最初构建 SessionFactory 时,可能有一种访问 CacheProvider 的方法,这将避免您自己实现的需要。

于 2009-04-01T03:40:25.247 回答
1

hibernate 和 JPA 现在都提供对底层二级缓存的直接访问:

sessionFactory.getCache();
entityManager.getCache();
于 2012-05-15T09:03:49.553 回答