天天看點

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讓實體對象集合對象緩存

繼續閱讀