考虑到效率和对数据库的压力,使用缓存或者内存缓存,可以提高反应速度和减轻数据库压力。hibernate中支持的比较多,在hibernate给的文档“提升性能”章节有详细介绍:
hibernate支持缓存类型和介绍:
后面三个还支持集群,比较强大。
现在详细介绍Ehcache使用:
Ehcache所需要的jar包(配合hibernate使用):
<ehcache> <!-- Sets the path to the directory where cache .data files are created. If the path is a Java System Property it is replaced by its value in the running VM. The following properties are translated: user.home - User's home directory user.dir - User's current working directory java.io.tmpdir - Default temp file path --> <diskStore path="java.io.tmpdir"/> <!--Default Cache configuration. These will applied to caches programmatically created through the CacheManager. The following attributes are required for defaultCache: maxInMemory - Sets the maximum number of objects that will be created in memory eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element is never expired. timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used if the element is not eternal. Idle time is now - last accessed time timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used if the element is not eternal. TTL is now - creation time overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit. --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /> </ehcache>
hibernate配置:
如果Query要缓存要手动设置的:
如果某个类有集合字段,我们也想要集合字段缓存,我们需要对那个字段设置缓存属性:
这种设置对于多级菜单很是有效的!
第一次(没的使用缓存的)效果:
第二次(缓存)效果: