<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div style="color: #4c1130;">In earlier we said that hibernate much more than an ORM tool i.e. Hibernate provide the lots of other features. In which Cache is very important feature one of them. Hibernate is actually a very powerful, consistent, and reliable database mapping tool. Mapping between objects in Java to relational databases has many facets that you must be aware of. Hibernate does a particularly good job of making the process simple to start, and providing the facilities to allow it to scale well and meet exceedingly complex mapping demands.</div>
<div></div>
<div style="color: #4c1130;">
<h2 id="ads-id" align="center"><strong>Caching in Hibernate </strong></h2>
<p>Caching is all about application performance optimization and it sits between your application and the database to avoid the number of database hits as many as possible to give a better performance for performance critical applications.</p>
<p>Caching is important to Hibernate as well which utilizes a multilevel caching schemes as explained below:</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2017/04/hibernate_cache.jpg" border="0" /></div>
</div>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;"><span style="color: red; font-size: x-large; text-align: center;"><b>Popular Tutorials</b></span></p>
<ul style="text-align: left;">
<li><b><a href="https://dineshonjava.com/spring-tutorial/"><em><strong>Spring Tutorial</strong> </em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-web-mvc-framework-chapter-38/"><strong><em>Spring MVC Web Tutorial </em></strong></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-spring-boot-a-spring-boot-complete-guide/"><strong>Spring Boot Tutorial</strong> </a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-take-baby-step-to-secure/"><em>Spring Security Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint/"><em>Spring AOP Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/using-spring-jdbc-framework-chapter-32/"><em>Spring JDBC Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-hateoas-hypermedia-driven-restful-web-service/"><em><strong>Spring HATEOAS </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/microservices-with-spring-boot/"><em><strong>Microservices with Spring Boot</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/jax-rs-web-service-tutorial/"><strong><em>REST Webservice</em> </strong></a></b></li>
<li><b><a href="https://dineshonjava.com/core-java-baby-step-to-be-best-java-ian/"><em><strong>Core Java </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/hibernate-3-on-baby-steps/"><em><strong>Hibernate Tutorial</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-batch-process-with-example/"><strong><em>Spring Batch</em> </strong></a></b></li>
</ul>
</div>
<div style="color: #4c1130;">One of the primary concerns of mappings between a database and our Java application is <b> performance</b>. This is the common concern of the all guys who working with hibernate and spent the more time in ORM tools for performance-enhancing changes to particular queries and retrievals. Today I want to discuss about some facets of the Hibernate infrastructure that are implemented to handle certain performance concerns &#8211;</div>
<ol style="color: #20124d; text-align: left;">
<li><b>The first-level cache &#8211; </b><b>Session </b>(Earlier hibernate already provide this level of cache)<b><br />
</b></li>
<li><b>The second-level cache &#8211;</b><b>Session-factory-level</b> cache</li>
<li><b>and the query cache. </b></li>
</ol>
</div>
<h2 style="color: blue;"><b>The first-level cache: </b></h2>
<div style="color: blue;">The first level cache type is the <b style="color: #20124d;">session cache</b>. The session cache caches object within the current session but this is not enough for long level i.e. session factory scope.</div>
<h2 style="color: blue;"><b>The second-level cache:</b></h2>
<div style="color: blue;">The second-level cache is called &#8216;second-level&#8217; because there is already a cache operating for you in Hibernate for the duration you have a session open. A Hibernate Session is a transaction-level cache of persistent data. It is possible to configure a SessionFactory-level cache on a class-by-class and collection-by-collection basis.</div>
<div style="color: blue;"><b> second-level cache</b><br />
&#8212; Across sessions in an Application<br />
&#8212; Across applications (different applications on same servers with same database)<br />
&#8212; Across clusters (different applications on different servers with same database)</div>
<div style="color: blue;"><b>NOTE</b>: Be careful Caches are never aware of changes made to the persistent store by another application i.e. suppose one application deploy one server with using hibernate and get the data from database and put to the cache for further using purpose but another application deployed another server which does not using any ORM tool so it does mot know about Cache and direct interacting with database and may be update data of database. Now data in Cache is invalid.</div>
<div style="color: blue;">
<p> ;</p>
<div style="color: #20124d;">
<p>Hibernate uses first-level cache by default and you have nothing to do to use first-level cache. Let&#8217;s go straight to the optional second-level cache. Not all classes benefit from caching, so it&#8217;s important to be able to disable the second-level cache.</p>
<p>The &#8216;second-level&#8217; cache exists as long as the session factory is alive. The second-level cache holds on to the &#8216;data&#8217; for all properties and associations (and collections if requested) for individual entities that are marked to be cached.</p>
</div>
<div style="color: #20124d;">In hibernate configuration file (hibernate.cfg.xml) we wrote the following line.<br />
For Disabling the second level of cache we have to made following change to hibernate configuration file.</div>
</div>
</div>
<pre class="highlight"><;!-- Disable the second-level cache -->; 
<;property name="cache.provider_class">;org.hibernate.cache.NoCacheProvider<;/property>; 
</pre>
</div>
<p> ;</p>
<div style="color: blue;">For Enabling the second level of cache we have to made following change to hibernate configuration file.</div>
<pre class="highlight"><;!-- Enable the second-level cache -->; 
<;property name="cache.use_second_level_cache">;true<;/property>; 
 <;property name="cache.provider_class">;org.hibernate.cache.EhCacheProvider<;/property>; 
</pre>
<div style="color: #20124d;"><b style="color: blue;">1. Cache Strategy using with Annotation as some changes made to the Model class a</b><b>lso.</b></div>
<pre class="highlight">@Cacheable 
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY) 
@Entity 
@Table(name="STUDENT") 
public class Student implements Serializable 
{ 
 .... 
</pre>
<div style="color: #20124d;">
<div style="color: #20124d;"><b style="color: blue;">2. Cache Strategy using with Mapping file(.hbm.xml) .</b><b></b></div>
<pre class="highlight"><;hibernate-mapping>; 
 <;class name="Student" table="STUDENT">; 
 
 This class contains the student detail. 
 
 <;cache usage="read-only">; 
 <;id column="ID" name="id" type="java.lang.Long">; 
 <;generator class="native">; 
 <;/generator>;<;/id>; 
 <;property column="STUDENT_NAME" name="studentName" type="java.lang.String">; 
 <;property column="lCOURSE" name="course" type="java.lang.String">; 
 <;property column="ROLL_NUMBER" name="rollNumber" type="java.lang.Long">; 
 <;/property>;<;/property>;<;/property>;<;/cache>;<;/class>; 
<;/hibernate-mapping>; 
</pre>
<div style="color: #20124d;"></div>
<h2 style="color: #20124d;">Concurrency strategies:</h2>
<div style="color: #20124d;">A concurrency strategy is a mediator which responsible for storing items of data in the cache and retrieving them from the cache. If you are going to enable a second-level cache, you will have to decide, for each persistent class and collection, which cache concurrency strategy to use.</div>
<ol style="color: #20124d;">
<li><b>Transactional:</b> Use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update.</li>
<li><b>Read-write:</b> Again use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update.</li>
<li><b>Nonstrict-read-write:</b> This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes and a small likelihood of stale data is not of critical concern.</li>
<li><b>Read-only:</b> A concurrency strategy suitable for data which never changes. Use it for reference data only.</li>
</ol>
<div style="color: #20124d;">You have to <a href="http://sourceforge.net/projects/ehcache/files/ehcache-core/ehcache-core-2.5.2/ehcache-core-2.5.2-distribution.tar.gz/download" target="_blank" rel="noopener">download </a>one more jar <b>(ehcache-core-2.5.2)</b> and configure with your application as given in below..</div>
</div>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2017/04/ehcache.jpg" border="0" /></div>
<div style="color: #20124d;">Now look the following example which describe the Second Level Of Cache i.e. Across the sessions.</div>
<p><b>HibernateTestDemo.java</b></p>
<pre class="highlight">package com.sdnext.hibernate.tutorial; 
 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.cfg.AnnotationConfiguration; 
 
import com.sdnext.hibernate.tutorial.dto.Student; 
 
 
public class HibernateTestDemo { 
 
 /** 
 * @param args 
 */ 
 public static void main(String[] args) 
 { 
 SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); 
 Session session = sessionFactory.openSession(); 
 session.beginTransaction(); 
 
 Student student = (Student) session.get(Student.class, 1); 
 
 session.getTransaction().commit(); 
 session.close(); 
 
 Session session2 = sessionFactory.openSession(); 
 session2.beginTransaction(); 
 
 Student student2 = (Student) session2.get(Student.class, 1); 
 
 session2.getTransaction().commit(); 
 session2.close(); 
 } 
} 
</pre>
<div style="background-color: #ff99cc; border-width: thin; border: solid;">
<div style="color: blue;"><b>Output:</b></div>
<p>log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).</p>
<div style="color: red;">log4j:WARN Please initialize the log4j system properly.</div>
<p>Hibernate: select student0_.ID as ID0_0_, student0_.COURSE as COURSE0_0_, student0_.ROLL_NUMBER as ROLL3_0_0_, student0_.STUDENT_NAME as STUDENT4_0_0_ from STUDENT student0_ where student0_.ID=?</p>
</div>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2017/04/ehcache1.jpg" border="0" /></div>
<p> ;</p>
<div style="color: #20124d;">As we seen the output there is only one query execute but we called get method for same model object two times i.e. when retrieve the model object first time it cache to the second level cache when we call second get of second session object for the same model object it does not execute select query again because hibernate return this model object from the session.</div>
<div style="color: #20124d;"></div>
<div style="color: #20124d;">
<p><b>In the <a href="https://dineshonjava.com/p/using-query-cache-in-hibernate.html">Next Chapter</a> we will discuss more about the <a href="https://dineshonjava.com/p/using-query-cache-in-hibernate.html">Query Caching in Hibernate.</a></b><br />
<b></b></p>
<p><;<;<a style="font-family: Times, 'Times New Roman', serif;" href="https://dineshonjava.com/p/understanding-restrictions.html">Previous Chapter 31</a><;<; >;>;<a href="https://dineshonjava.com/p/using-query-cache-in-hibernate.html">Next Chapter 33</a>>;>;</p>
</div>
</div>
<p> ;</p>
</div>