Apr 21, 2016

Hibernate EHCache Second Level Caching Example(Hibernate 4.x + Maven + MySQL 5.x)

1. Eclipse Project Structure



2. Java Code

2.1.Employee.java ( Entity Class)

package com.test.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Table(name = "employee")
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region = "employee")
public class Employee {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "id")
 private int id;
 @Column(name = "firstname")
 private String firstName;
 @Column(name = "lastname")
 private String lastName;
 @Column(name = "telephone")
 private String telephone;
 @Column(name = "email")
 private String email;
 public Employee() {
 }
 public Employee(String firstName, String lastName, String telephone,
   String email) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
  this.telephone = telephone;
  this.email = email;
 }
 public int getId() {
  return id;
 }
 public String getFirstName() {
  return firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public String getTelephone() {
  return telephone;
 }
 public String getEmail() {
  return email;
 }
 @Override
 public String toString() {
  return "Employee [Employee ID=" + id + ", FirstName=" + firstName
    + ", LastName=" + lastName + ",Telephone=" + telephone
    + ",Email=" + email + "]";
 }
}

2.2.HibernateUtility.java

package com.test.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtility {

 private static final SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory() {
  Configuration configuration = new Configuration();
  configuration.configure();
  ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
    .applySettings(configuration.getProperties()).build();
  SessionFactory sessionFactory = configuration
    .buildSessionFactory(serviceRegistry);
  return sessionFactory;
 }
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}
2.3.SecondLevelCacheTest.java

package com.test.service;
import org.hibernate.Session;
import com.test.entity.Employee;
import com.test.util.HibernateUtility;
public class SecondLevelCacheTest {

 public static void main(String[] args) {
 
  Session session = HibernateUtility.getSessionFactory().openSession();
  session.beginTransaction();
  Employee employee = null;
  System.out.println("=============================================================");
  employee = (Employee) session.load(Employee.class, 1);
  System.out.println("Employee details from the Database :: " + employee);
  System.out.println("=============================================================");
  System.out.println("Printing Employee details from First Level Cache");
  // Second time loading the same Employee entity from the first level cache
  employee = (Employee) session.load(Employee.class, 1);
  System.out.println(employee);
  System.out.println("=============================================================");
  // Removing Employee object from the first level cache.
  session.evict(employee);
  System.out.println("Object removed from the First Level Cache");
  System.out.println("=============================================================");
 
  System.out.println("Printing Employee details from Second level Cache");
  employee = (Employee) session.load(Employee.class, 1);
  System.out.println(employee);
  session.getTransaction().commit();
  System.out.println("=============================================================");
  // Loading object in another session
  Session session2 = HibernateUtility.getSessionFactory().openSession();
  session2.beginTransaction();
  System.out.println();
  System.out.println("Printing Employee details from Second level Cache in another session");
  employee = (Employee) session2.load(Employee.class, 1);
  System.out.println(employee);
  session2.getTransaction().commit();
 }
}
3.ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
 <diskStore path="D:/tmp" />
 <defaultCache maxEntriesLocalHeap="4000" eternal="false"
  timeToIdleSeconds="60" timeToLiveSeconds="120" diskSpoolBufferSizeMB="20"
  maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
  memoryStoreEvictionPolicy="LRU" statistics="true">
  <persistence strategy="localTempSwap" />
 </defaultCache>
 <cache name="employee" maxEntriesLocalHeap="4000" eternal="false"
  timeToIdleSeconds="5" timeToLiveSeconds="10">
  <persistence strategy="localTempSwap" />
 </cache>
 <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
  maxEntriesLocalHeap="5000" eternal="true">
  <persistence strategy="localTempSwap" />
 </cache>
</ehcache>

4.hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt;
<hibernate-configuration>

 <session-factory>

  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost:3306/nadhu</property>
  <property name="connection.username">root</property>
  <property name="connection.password">knmuni</property>
  <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
  <!-- Enable Second Level Cache -->
  <property name="hibernate.cache.use_second_level_cache">true</property>
  <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property>
  <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>
  <property name="format_sql">true</property>
  <property name="hbm2ddl.auto">update</property>
  <mapping class="com.test.entity.Employee" />
 </session-factory>

</hibernate-configuration>

5.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
 <modelVersion>4.0.0</modelVersion>
 <groupId>Hibernate-SecondLevelCache-Demo</groupId>
 <artifactId>Hibernate-SecondLevelCache-Demo</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>Hibernate-SecondLevelCache-Demo</name>
 <dependencies>
  <!-- Hibernate Dependency -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.7.Final</version>
  </dependency>
  <!-- MySql Connector dependency -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.10</version>
  </dependency>
  <!-- EhCache Core APIs -->
  <dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache-core</artifactId>
   <version>2.6.9</version>
  </dependency>
  <!-- Hibernate Integration EhCache API -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-ehcache</artifactId>
   <version>4.3.5.Final</version>
  </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
  </plugins>
 </build>

</project>

6. Output

INFO: HHH000126: Indexes: [primary]
Apr 21, 2016 6:18:41 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
 
=============================================================

Hibernate:

select

employee0_.id as id1_0_0_,

employee0_.email as email2_0_0_,

employee0_.firstname as firstnam3_0_0_,

employee0_.lastname as lastname4_0_0_,

employee0_.telephone as telephon5_0_0_

from

employee employee0_

where

employee0_.id=?

Employee details from the Database :: Employee [Employee ID=1, FirstName=Jon, LastName=Stephens,Telephone=0000000003,Email=jon.s@abc.com]

=============================================================

Printing Employee details from First Level Cache

Employee [Employee ID=1, FirstName=Jon, LastName=Stephens,Telephone=0000000003,Email=jon.s@abc.com]

=============================================================

Object removed from the First Level Cache

=============================================================

Printing Employee details from Second level Cache

Employee [Employee ID=1, FirstName=Jon, LastName=Stephens,Telephone=0000000003,Email=jon.s@abc.com]

=============================================================

Printing Employee details from Second level Cache in another session

Employee [Employee ID=1, FirstName=Jon, LastName=Stephens,Telephone=0000000003,Email=jon.s@abc.com]


 Thank you ! :)


 

14 comments:

Unknown said...

All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.

automation anywhere training in chennai

automation anywhere training in bangalore

automation anywhere training in pune

automation anywhere online training

blueprism online training

rpa Training in sholinganallur

rpa Training in annanagar

iot-training-in-chennai

blueprism-training-in-pune

automation-anywhere-training-in-pune

nivatha said...

I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.

Data Science with Python training in chenni
Data Science training in chennai
Data science training in velachery
Data science training in tambaram
Data Science training in OMR
Data Science training in anna nagar
Data Science training in chennai
Data science training in Bangalore

simbu said...

I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.

java training in marathahalli | java training in btm layout

java training in jayanagar | java training in electronic city

java training in chennai | java training in USA

selenium training in chennai

Unknown said...

Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!
python training in pune
python online training
python training in OMR

Anonymous said...

I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post I would like to read this
Blueprism training institute in Chennai

Blueprism online training

chitra pragya said...

This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolites festivity to pity. I appreciated what you ok extremely here 
angularjs Training in bangalore

angularjs Training in btm

angularjs Training in electronic-city

angularjs online Training

angularjs Training in marathahalli

Ishu Sathya said...

Your website is very cool and it is a wonderfully inspiring article. thank you so much.

selenium training in tambaram
selenium training in adyar
iOS Training in Chennai
French Classes in Chennai
Big Data Training in Chennai
PHP Training
Best PHP training in chennai

jvimala said...

I would like to appreciate you for making it very simple and easy
Regards,
PHP Training in Chennai | PHP Course in Chennai

Unknown said...

I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post I would like to read this

devops online training

aws online training

data science with python online training

data science online training

rpa online training

Realtime Experts said...

It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful ..Automation Anywhere Training in Bangalore

Unknown said...

I would definitely thank the admin of this blog for sharing this information with us. Waiting
for more updates from this blog admin.

Salesforce Training | Online Course | Certification in chennai | Salesforce Training | Online Course | Certification in bangalore | Salesforce Training | Online Course | Certification in hyderabad | Salesforce Training | Online Course | Certification in pune

divya said...

Probably the most unique feature of our team is the fact that QuickBooks Payroll Support Phone Number really is designed for you 24*7. They work hard towards offering you the very best customer service and focus on achieving maximum customer care thanks
Ai & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai

Unknown said...

instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al

DSM infotech said...

Nice content sharing, it is very useful to us.
sap training in btm layout