一、 Ehcache配置文件ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache name="es">
<diskStore path="java.io.tmpdir"/>
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="30" timeToLiveSeconds="30" overflowToDisk="true"> </defaultCache> </ehcache> |
注意该配置文件须放置在项目的classpath中
二、 Hibernate配置二级缓存
在hibernate的LocalSessionFactoryBean这个bean的配置中添加二级缓存的配置项:
<!-- 开启二级缓存 --> <prop key="hibernate.cache.use_second_level_cache">true</prop> <!-- 启动"查询缓存"如果想缓存使用findall()、list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集,必须配置此项--> <prop key="hibernate.cache.use_query_cache">true</prop> <!-- 高速缓存提供程序 --> <!-- 由于spring也使用了Ehcache, 保证双方都使用同一个缓存管理器 --> <prop key="hibernate.cache.region.factory_class"> org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory </prop> |
其中
<prop key="hibernate.cache.region.factory_class">
org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
</prop>
是当spring也配置了ehcache作为缓存时,为了使spring缓存和hibernate缓存使用同一缓存管理器,从而保证缓存的一致性,需要使用org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory。如果仅是hibernate使用ehcache的话,org.hibernate.cache.ehcache.EhCacheRegionFactory即可。
三、 Hibernate映射实体的缓存配置
为了使hibernate缓存相应的实体对象,需要在实体映射配置的实体类的第一行添加cache配置,如下:
<class name="User" table="User"> <cache usage="read-write"/> … </class> |
在代码中使用Query的list等查询方法时,默认是不会自动缓存实体对象的,需要调用Query的方法query.setCacheable(true).list();来进行缓存即可。