二级缓存:
- jar包两个
commons-logging.jar
ehcache-1.2.3.jar - 总配置文件
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<mapping resource="entity/dept.hbm.xml" />
ehcache.xml
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<!--Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)。-->
<!--eternal:是否是永恒数据,如果是,则它的超时设置会被忽略。-->
<!--timeToIdleSeconds:对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问。-->
<!--timeToLiveSeconds:对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问。-->
<!--overflowToDisk:如果内存中数据数量超过maxElementsInMemory限制,是否要缓存到磁盘上。-->
<cache name="entity.Emp"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<cache name="entity.Dept"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>
</ehcache>
查询缓存:
二级缓存仍然只能缓存get()/load()方法获取的session数据;
如果想要缓存HQL语句的session数据,需要采用查询缓存(use-_query_cache)。
- 开启了二级缓存
- 总配置文件
<property name="hibernate.cache.use_query_cache">true</property>
- HQL查询时,加入
query.setcatchable(true)
Emp e=(Emp) query.setCacheable(true).uniqueResult();