我已经阅读了很多答案并查看了ehcache文档,但我就是找不到这个问题的解决方案。Ehache只是不想为我工作。
我使用的是spring 4.1.6版本和hibernate 4.3.5最终版本,我想启用缓存,这样我就不必每次都访问DB了。
这是我的pom.xml的一部分:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate-version}</version>
</dependency>
这是hibernate.cfg.xml的相关部分:
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
这是ehcache.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir"/>
<defaultCache
eternal="false"
maxElementsInMemory="100"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
<cache name="model.entities.User" maxElementsInMemory="100" eternal="true" timeToIdleSeconds="300" timeToLiveSeconds="600" />
</ehcache>
一个问题是,如果我将maxEntriesLocalHeap属性添加到defaultCache,我会得到
error: Element <defaultCache> does not allow attribute "maxEntriesLocalHeap".
尽管XSD指定defaultCache的属性为"maxEntriesLocalHeap“。我不太关心这个参数,所以我删除了它,但它就是很奇怪。好吧,至少我知道这一点:)阅读ehcache.xml。我之所以知道这一点,也是因为我得到的输出如下:
WARN : org.hibernate.cache.ehcache.AbstractEhcacheRegionFactory - HHH020003: Could not find a specific ehcache configuration for cache named [model.entities.Role]; using defaults.
而且在这个输出中没有User类,所以在ehcache.xml中添加最后一个缓存标记确实有一些效果。
我必须说,我还在每个hbm.xml文件中放入了这一行:
<cache usage="read-write" />
这一切似乎都在工作,我没有得到任何错误,但查看mysql日志文件显示,mysql服务器非常频繁地使用相同的参数进行相同的select查询,尽管此行没有被修改。这就是我想要避免的。
我在spring配置文件中没有做任何具体的事情。我应该吗?
提前感谢您的帮助。我都快为这事发疯了。
发布于 2015-05-02 04:05:30
我很着急,我认为这可以开箱即用,而不需要对代码进行任何更改。但事实并非如此。
几天后,当我终于有时间认真对待这个问题时,我发现我从未将Hibernate Query对象的cacheable属性设置为true。
如下所示:
query.setCacheable(true);
就是这样。它现在起作用了。在事务支持方面仍然存在一些问题,但重要的是缓存能够正常工作:)
https://stackoverflow.com/questions/29883903
复制相似问题