Hibernate缓存-使用Ehcache让实体对象集合对象缓存

考虑到效率和对数据库的压力,使用缓存或者内存缓存,可以提高反应速度和减轻数据库压力。hibernate中支持的比较多,在hibernate给的文档“提升性能”章节有详细介绍:

image

hibernate支持缓存类型和介绍:

image

后面三个还支持集群,比较强大。

现在详细介绍Ehcache使用:

Ehcache所需要的jar包(配合hibernate使用):

imageimageimage加入配置文件:image

<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配置:

image

如果Query要缓存要手动设置的:

image

如果某个类有集合字段,我们也想要集合字段缓存,我们需要对那个字段设置缓存属性:

image

image

这种设置对于多级菜单很是有效的!

第一次(没的使用缓存的)效果:

image

第二次(缓存)效果:

image

posted @ 2011-11-19 12:06  BuildNewApp  阅读(3177)  评论(0编辑  收藏  举报