java – 操作Hibernate二级缓存

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

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

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

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

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

最佳答案
我会在映射到您的实体的EntityPersister上调用“afterInsert”,因为Read / Write是一种异步并发策略.在查看Hibernate 3.3源代码后,我将它拼凑在一起.我不是百分之百,这会起作用,但它对我来说很好看.

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;

转载注明原文:java – 操作Hibernate二级缓存 - 代码日志