[英]EHCache + hibernate: multiple queries to database
我将我的应用程序配置为使用查询缓存。
休眠配置:
hibernate.cache.region.factory_class=net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory
hibernate.cache.use_query_cache=true
EHCache 配置:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="false">
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<cache name="query.Dictionary.CountriesList"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="1000"
eternal="false"
timeToLiveSeconds="86400">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
道:
Criteria query = session.createCriteria(DictionaryCountry.class)
.setCacheable(true)
.setCacheRegion("query.Dictionary.CountriesList")
.addOrder(Order.asc("name"));
现在,当我第一次尝试填充国家/地区列表时 - 进行了标准查询(select * from ... where ... )
。 但是当我第二次这样做时 - 应用程序不是从缓存中获取,而是执行了很多 get by id sql 查询(select * from ... where id = ? )
...
这是正常行为吗?
谢谢
很长一段时间后,但今天我遇到了同样的问题,如果有人需要 ehcache+spring+hibernate 的帮助,这里是一个答案
之前的配置是正确的,我只会添加下一个:
1.- 添加: <property name="hibernate.cache.use_second_level_cache">true</property>
2.- 在您的模型中设置
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE )
3.- 添加这样的东西,使您的模型可缓存
<cache name="com.yourcompany.yourproyect.model.DictionaryCountry
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="1000"
eternal="false"
timeToLiveSeconds="86400">
<persistence strategy="localTempSwap" />
</cache>
query.setCacheable(true);
必需使您的模型可缓存query.setCacheRegion("query.Dictionary.CountriesList");
可选,因为可以在查询级别缓存
ehcache 版本:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.5</version>
</dependency>
我认为就是这样,因为这对我有用。
是的,查询缓存需要二级缓存。 这是我的配置:
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property><code>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</property>
<property name="hibernate.cache.use_structured_entries">true</property>
<property name="hibernate.generate_statistics">true</property>
关于对数据库问题的多个查询,我发现的真正错误在这里
使用 var1 = 1 和 var2 = 20。
List<entity> objects = session.createCriteria(entity.class)
.add(Restrictions.between("price",var1,var2))
.setCacheable(true)
.list();
问题是:如果我使用var1 = 21
和var2 = 40
执行后续查询,则 ehcache 不够智能,无法从缓存中检索,因为这些对象已经从前一个查询中缓存了。
我在一个查询中遇到了动态参数的问题,所以二级缓存从未被命中,因为查询总是不同的,它需要具有相同的参数。
希望它有所帮助,因为这是我的经验。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.