我使用Hibernate作为ORM我的解决方案,为的EHCache第二级(读写)高速缓存。

我的问题是:是否有可能直接进入二级缓存?

我想访问此: HTTP:// www.hibernate.org/hib_docs/v3/api/org/hibernate/cache/ReadWriteCache.html

如何访问正在使用由Hibernate相同ReadWriteCache?

我有一些直接/自定义JDBC插入,我做什么,我希望将这些对象添加到第2级缓存自己。

有帮助吗?

解决方案

我称之为“afterInsert”关于映射到你的实体,因为读/写是异步并发策略的EntityPersister。我通过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;

其他提示

我创造我自己的缓存提供这样做。我只是推翻EhCacheProvider并使用了自己变量的经理,所以我可以在静态返回。一旦你得到了CacheManager中,你可以调用manager.getCache(CLASS_NAME),以获取该实体类型的高速缓存。然后,你使用主键,类型,和类名建立一个CacheKey:

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

缓存本质上是一个地图,这样你可以检查看看,如果你的对象是在缓存中,或者通过实体迭代。

有可能是当你建立SessionFactory的最初这将避免需要实现自己的访问的CacheProvider的方式。

Hibernate和JPA现在提供到底层第二级高速缓存直接访问:

sessionFactory.getCache();
entityManager.getCache();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top