问题
I have enabled 2nd level caching in Hibernate 4.3.11 by adding:
config.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory");
config.setProperty("hibernate.cache.use_second_level_cache", "true");
to my Hibernate Config.
This to my pom.xml (Not sure if necessary for pom definition to be this awkward)
<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>
and this to the class I want to cache
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
But how do I configure the cache size in code when the database is created, its not practical for me to use Xml file that just adds complication to the build process I would much prefer to do in code.
Update, after creating database from Hibernate, I find the Caches are already created
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);
}
but how can I affect how they are created or does modifying values like i have done is enough to update. When I run I see no debugging outout or anything to indicate the cache is being used.
回答1:
You could subclass org.hibernate.cache.ehcache.EhCacheRegionFactory
and perform any cache configuration manually, and then tell Hibernate to use your custom cache factory with:
Configuration.setProperty("hibernate.cache.region.factory_class", "my.cache.FactoryClass");
See: http://www.ehcache.org/documentation/2.7/integrations/hibernate.html#set-the-hibernate-cache-provider-programmatically-
来源:https://stackoverflow.com/questions/52823657/when-how-do-i-set-ehcache-used-by-hibernate-size-programmatically