您可以尝试使用一个缓存并在其周围添加装饰器。装饰器的名称可以与您的区域名称匹配,以便hibernate可以使用这些缓存,但是这些装饰器将在下面使用相同的缓存。因此,只有一个缓存配置可以管理。您可以通过实现自定义缓存装饰器并设置装饰的缓存的名称来实现。
您可以拥有ehcache.xml这样的内容:
<defaultCache maxElementsInMemory="10000" eternal="false"
overflowToDisk="false"/>
<cache name="singleSharedCache" maxElementsInMemory="2000"
eternal="false" overflowToDisk="false">
<cacheDecoratorFactory class="com.xyz.util.CustomEhcacheDecoratorFactory"
properties="name=org.hibernate.tutorial.domain.Person" />
<cacheDecoratorFactory class="com.xyz.util.CustomEhcacheDecoratorFactory"
properties="name=org.hibernate.tutorial.domain.Event" />
</cache>
“ com.xyz.util.CustomEhcacheDecoratorFactory”是一个自定义ehcache装饰器工厂类,用于创建装饰后的ehcache。您可以使用“ properties”属性以所需的任何方式设置修饰的ehcache,在这里,您仅使用name属性来配置新修饰的ehcache的名称。可以将所有其他操作委托给基础缓存。
提供了一个适用于此用例的自定义缓存装饰器,它重用了ehcache jar中附带的EhcacheDecoratorAdapter,并且仅覆盖了getName()。EhcacheDecoratorAdapter将所有操作委托给您在构造函数中传递的基础ehcache:
包com.xyz.util;
导入java.util.Properties;
导入net.sf.ehcache.Ehcache;
导入net.sf.ehcache.constructs.CacheDecoratorFactory;
导入net.sf.ehcache.constructs.EhcacheDecoratorAdapter;
公共类CustomEhcacheDecoratorFactory扩展了CacheDecoratorFactory {
公共Ehcache createDecoratedEhcache(最终Ehcache缓存,
最终属性属性){
返回新的EhcacheDecoratorAdapter(cache){
私有最终字符串名称= properties.getProperty(“ name”);
公共字符串getName(){
返回名称;
}
};
}
公共Ehcache createDefaultDecoratedEhcache(最终Ehcache缓存,
最终属性属性){
返回新的EhcacheDecoratorAdapter(cache){
私有最终字符串名称= properties.getProperty(“ name”);
公共字符串getName(){
返回名称;
}
};
}
}