hibernate配置缓存查询

先在src目录下加入ehcache.xml文件:

<?xml version="1.0" encoding="UTF-8"?> <ehcache> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> <cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="50" eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="3600" overflowToDisk="true" /> <cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="5000" eternal="true" overflowToDisk="true" /> <cache name="myCacheRegion" maxElementsInMemory="10" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="true" /> </ehcache>

在hibernate配置文件中或spirng管理hibernate类当中加入:

<property name="cache.use_query_cache">true</property> <property name="cache.use_second_level_cache">true</property> <property name="cache.provider_class"> org.hibernate.cache.EhCacheProvider </property>

Dao中加入如下代码就能使用查询缓存了 

 Query q  = this.getSession(false).createQuery(hql).setCacheable(true);

 

忘了补充一点:查询缓存是针对相同条件的查询和全体查询,而二级缓存是针对主键查询。

如果同时需要启动二级缓存又要启动查询缓存, 希望是同时同步的,如果不同步,假设只有二级缓存而没有查询缓存还可以,

但只有查询缓存没有二级缓存,hibernate会把查询结果再用主键查找一次,这样就加大了数据库的交互。

 

你可能感兴趣的:(Hibernate,数据库,query,360,encoding)