何时/如何以编程方式设置休眠大小使用的Ehcache

时间:2018-10-15 19:40:16

标签: hibernate ehcache hibernate-4.x

我通过添加以下内容在Hibernate 4.3.11中启用了二级缓存:

 config.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory");
 config.setProperty("hibernate.cache.use_second_level_cache", "true");

进入我的Hibernate Config。

将其发送到我的pom.xml中(不确定是否需要将pom定义设置为这种尴尬)

<dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
      <version>4.3.11.Final</version>
      <exclusions>
          <exclusion>
              <groupId>net.sf.ehcache</groupId>
              <artifactId>ehcache-core</artifactId>
          </exclusion>
      </exclusions>
      </dependency>
      <dependency>
          <groupId>net.sf.ehcache</groupId>
          <artifactId>ehcache</artifactId>
          <version>2.7.0</version>
      </dependency>

这是我要缓存的类

@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

但是创建数据库时如何在代码中配置缓存大小,使用Xml文件对我来说不现实,因为Xml文件只会使我更喜欢在代码中进行构建的过程更加复杂。

更新,从Hibernate创建数据库后,我发现缓存已经创建

CacheManager.create();
String[] cacheNames = CacheManager.getInstance().getCacheNames();
for(String cacheName:cacheNames)
{
    MainWindow.logger.severe("CacheName:"+cacheName);
    Cache cache = CacheManager.getInstance().getCache(cacheName);
    cache.getCacheConfiguration().setMaxEntriesInCache(1000);
    cache.getCacheConfiguration().setLogging(true);
}

但是我如何影响它们的创建方式或像我所做的那样修改值足以更新。当我运行时,我看不到任何调试信息,也没有任何迹象表明正在使用缓存。

1 个答案:

答案 0 :(得分:1)

您可以继承org.hibernate.cache.ehcache.EhCacheRegionFactory的子类并手动执行任何缓存配置,然后告诉Hibernate通过以下方式使用您的自定义缓存工厂:

Configuration.setProperty("hibernate.cache.region.factory_class", "my.cache.FactoryClass");

请参阅:http://www.ehcache.org/documentation/2.7/integrations/hibernate.html#set-the-hibernate-cache-provider-programmatically-