2012-08-06 72 views
5

我已閱讀關於此主題的其他線索,但沒有解決方案適用於我。如何在Hibernate 4.1.5 SP1中配置二級緩存?

我試圖把這個在我的hibernate.cfg.xml:

<property name="hibernate.cache.region.factory_class">org.hibernate.cache.spi.EntityRegion</property> 

我總是得到這樣的錯誤: 不能實例RegionFactory [org.hibernate.cache.spi.EntityRegion]

我也嘗試了Hibernate網站上的大多數線程建議,但沒有運氣。

那麼如何配置呢?

回答

11

好了,我找到了答案(由YouTube用戶):

To get it working:

1) I use hibernate-release-4.1.0.Final or later versions. So I've added jars from its lib\optional\ehcache directory

2) My hibernate.cfg.xml contains:

<property name="cache.region.factory_cla­ss">org.hibernate.cache.ehcache.Si­ngletonEhCacheRegionFactory</property> 

3) Finally I had to add slf4j-api-1.6.1.jar (I found it in ehcache-2.5.1-distribution.tar­.gz downloaded from ehcache.org in addition) because of ClassNotFoundException.

此外,如果你還沒有這樣做了,將它添加到您的hibernate.cfg.xml:

<!-- Enable Hibernate's automatic session context management --> 
<property name="cache.use_second_level_cache">true</property> 

這裏的關鍵是從Hibernate4的可選\目錄中添加ehcache jar。

2

將以下屬性添加到Hibernate屬性:

<prop key="hibernate.cache.use_second_level_cache">true</prop> 
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> 
<prop key="hibernate.cache.provider_configuration_file_resource_path">hibernate-ehcache.xml</prop> 
<prop key="hibernate.cache.use_query_cache">true</prop> 
<prop key="hibernate.generate_statistics">true</prop> 
<prop key="hibernate.cache.use_structured_entries">true</prop> 

您需要的Hibernate 4.1.1 ehcache的罐子與否的Ehcache罐子。

請記下已更改的緩存提供程序類。

1

希望對某些人來說(hibernate 4.x)有些用處。

從我的配置方式,摘錄:

public Properties hibernateProperties() { 
    Properties properties = new Properties(); 
    properties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); 
    properties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); 
    properties.setProperty("hibernate.format_sql", "true"); 
    properties.setProperty("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics")); 
    // second-level cache: 
    properties.setProperty("hibernate.cache.use_second_level_cache", "true");   
    properties.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.EhCacheRegionFactory"); 
    properties.setProperty("net.sf.ehcache.configurationResourceName", env.getProperty("net.sf.ehcache.configurationResourceName")); 
    return properties; 
} 

你必須有'org.hibernate作爲:休眠-的Ehcache:HIBERNATE_VERSION在您的類路徑中。

參見:Ehcache doc on hibernate configuration