最近要做一个小东西,自己学着用一下hibernate 的二级缓存,虽然说就是几个配置的问题,不过搞得不好,配置中会发生很多问题。
以在我们用hibernate3.2中,我们配置二级缓存如下:
<property name="cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_query_cache">true</property>
另外在jar中,我们用的是\lib\optional\ehcache\ehcache1.23.jar
但是今天我在做测试的时候,用得是hibernate-core-4.1.2-final版本,做了半天也没有成功,最后在网上不断的找资料,最终找到错误原因:
在hibernate4中,配置cache与hibernate3.2是不一样的
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">901206</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>
<property name="show_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.Stu001"/>
</session-factory>
其中:
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
改为:
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>
<property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>
这个属性可以不写,hibernate会默认的到classess 中找到ehcache.xml,如果你自己不是用默认的名ehcache.xml,那么你就必须得写这了属性。
哎,搞半天可以了,希望能为后面的学习人少走弯路,提供一个借鉴。
ehcache.xml配置如下:
<diskStore path="d:/temp"/>,配置这个之后
在d:/temp中会增加三个文件
com.Stu001.data
org.hibernate.cache.internal.StandardQueryCache.data
org.hibernate.cache.spi.UpdateTimestampsCache.data