Monday 12 June 2017

Difference between First and Second Level Cache in Hibernate

Hibernate Provides Cache at different Levels:
1. first level cache -- session (enabled by default)
2. Second level cache - session factory  (need to configure)

This session level cache greatly improves the performance of Java application by minimizing database roundtrips and executing less number of queries. For example, if an object is modified several times within the same transaction, then Hibernate will only generate one SQL UPDATE statement at the end of the transaction, containing all the modification.

Second level cache can be configured using ehCache or OSCache

Here is a sample configuration to configure Second level cache with EhCache:

<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>

Don't forget to include hibernate-ehcache.jar into your classpath.

Difference between First and Second Level Cache in Hibernate

You can also use JPA Annoation @Cacheable to specify which entity is cacheable. and Hibernate annoation @Cache to specify caching startegy e.g. CacheConcurrencyStrategies like READ_WRITE or READ_ONLY to tell Hibernate how the second level cache should behave.