How to enable second level cache in Hibernate

2019-06-24 02:44发布

I need some pojo objects across my application so I want to know how to enable Second Level Cache. Until now by default First Level cache is enabled, I would also like to know what advantages and disadvantages of Second Level cache there are.

3条回答
聊天终结者
2楼-- · 2019-06-24 03:33

This is what you need to do:

  1. Set the following Hibernate properties:

    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
    
  2. Add an ehcache.xml file in your classpath, containing the cache configuration entries:

    <cache name="com.mycompany.MyEntity"
       maxElementsInMemory="50"
       eternal="true"
       overflowToDisk="false"
       timeToIdleSeconds="600"
       timeToLiveSeconds="600"
       diskPersistent="false"
       memoryStoreEvictionPolicy="LRU"       
    />
    
  3. Define the Caching type for each entity:

    @Entity
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public class MyEntity {
            ...
    }
    
查看更多
趁早两清
3楼-- · 2019-06-24 03:40

Second level cache was introduced in hibernate 3.0

When ever we are loading any object from the database, then hibernate verify whether that object is available in the local cache memory of that particular session [ means first level cache ], if not available then hibernate verify whether the object is available in global cache or factory cache [ second level cache ], if not available then hibernate will hit the database and loads the object from there, and then first stores in the local cache of the session [ first level ] then in the global cache [ second level cache ]

When ever we are loading any object from the database, then hibernate verify whether that object is available in the local cache memory of that particular session [ means first level cache ], if not available then hibernate verify whether the object is available in global cache or factory cache [ second level cache ], if not available then hibernate will hit the database and loads the object from there, and then first stores in the local cache of the session [ first level ] then in the global cache [ second level cache ]

查看更多
太酷不给撩
4楼-- · 2019-06-24 03:45

JPA L2 cache is enabled, configured using the persistence property

javax.persistence.sharedCache.mode

which has values of NONE | ALL | ENABLE_SELECTIVE | DISABLE_SELECTIVE | UNSPECIFIED. Using this property is common across ALL valid JPA implementations.

查看更多
登录 后发表回答