Easy learning with example program codes

second level cache in hibernate

Second level cache is implemented by session factory objects. It is not enabled by default. It uses common cache for all session objects i.e. available for all session objects.

We have to use third party implementations to implement second level cache in hibernate. Some of the third party implementations are given below:

  • EH Cache
  • OS Cache
  • Swarm Cache
  • JBoss Cache

Ways to use second level cache (concurrency strategy).

  • read-only: Used for read only operation.
  • nonstrict-read-write: Used for read and write but one at a time.
  • read-write: Used for read and write, can be used simultaneously.
  • transactional: Used for transaction.

Concurrency strategy with second level implementation providers

Strategy/Provider Read-only Nonstrictread-write Read-write Transactional
EHCache Yes Yes Yes No
OSCache Yes Yes Yes No
SwarmCache Yes Yes No No
JBoss Cache No No No Yes


To enable second level cache we need to make the following changes in hibernate configuration file.

//Enable the second level cache
<property name="cache.use_second_level_cache">true</property>
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

Cache strategy using annotations:

@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Employee implements Serializable {

Cache strategy using xml:

   <class name="Employee" table="EMPLOYEE">      
      <cache usage="read-only">
      <id column="ID" name="id" type="java.lang.Long">
         <generator class="native">

Copyright © 2018 CodesJava Protection Status SiteMap