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.
-
http://stackoverflow.com/questions/1216630/hibernate-second-level-cache-net-sf-ehcache-hibernate-ehcacheprovider or http://stackoverflow.com/questions/20584585/hibernate-second-level-cache-example – StanislavL Dec 08 '14 at 12:36
-
possible duplicate-http://stackoverflow.com/questions/27358121/how-to-enable-second-level-cache-in-hibernate – Navish Sharma Dec 08 '14 at 12:39
3 Answers
This is what you need to do:
Set the following Hibernate properties:
<property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.provider_class">ehcache</property>
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" />
Define the Caching type for each entity:
@Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class MyEntity { ... }

- 142,745
- 71
- 566
- 911
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 ]

- 103
- 10
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.

- 11,383
- 3
- 34
- 29