如何在Hibernate 4.1.5 SP1中配置二级缓存?

时间:2012-08-06 16:36:34

标签: hibernate second-level-cache hibernate-4.x

我已经在这里阅读了关于这个主题的其他主题,但没有一个解决方案适合我。

我尝试将它放在我的hibernate.cfg.xml中:

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

我总是收到此错误: 无法实例化RegionFactory [org.hibernate.cache.spi.EntityRegion]

我也尝试过Hibernate网站上的大多数建议,但没有运气。

那么如何配置呢?

3 个答案:

答案 0 :(得分:12)

好吧,我找到了答案(来自Youtube用户):

  1. 使用hibernate-release-4.1.0.Final或更高版本。
  2. 从lib \ optional \ ehcache目录
  3. 添加jar
  4. 更新hibernate.cfg.xml

    <property name="cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property>
    
  5. 添加slf4j-api-1.6.1.jar(我在ehcache-2.5.1-distribution.tar.gz中找到了它 因为ClassNotFoundException而从ehcache.org下载。

  6. 将其添加到您的hibernate.cfg.xml:

    <!-- Enable Hibernate's automatic session context management -->
    <property name="cache.use_second_level_cache">true</property>
    
  7. 这里的关键点是从Hibernate4中的可选\目录添加ehcache jar。

答案 1 :(得分:3)

将以下属性添加到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-ehcache 4.1.1 jar或不是ehcache jar。

请记下已更改的缓存提供程序类。

答案 2 :(得分:2)

希望,它可能会对某些人有用(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;
}

你必须拥有&#39; org.hibernate:hibernate-ehcache:HIBERNATE_VERSION&#39;在你的课程路径上。

请参阅:Ehcache doc on hibernate configuration