CodesJava

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/ProviderRead-onlyNonstrictread-writeRead-writeTransactional
EHCacheYesYesYesNo
OSCacheYesYesYesNo
SwarmCacheYesYesNoNo
JBoss CacheNoNoNoYes

 

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:

@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Entity
@Table(name="EMPLOYEE")
public class Employee implements Serializable {
}

Cache strategy using xml:

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">      
      <cache usage="read-only">
      <id column="ID" name="id" type="java.lang.Long">
         <generator class="native">
      </generator></id></cache>
  </class>
</hibernate-mapping>
Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status