简体   繁体   中英

How to enable second level cache in Hibernate

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.

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">ehcache</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 { ... }

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 ]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM