天天看点

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

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

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

hibernate支持缓存类型和介绍:

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

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

现在详细介绍Ehcache使用:

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

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

加入配置文件:

Hibernate缓存-使用Ehcache让实体对象集合对象缓存
<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配置:

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

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

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

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

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

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

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

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

第二次(缓存)效果:

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

继续阅读