Here we demonstrate the second level cache of hibernate using ehcache.Here in this example we are using one entity student and READ_ONLY cache strategy to handle cache.
StudentInfo.java
package com.nik.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Table(name = "student")
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY,region="studentCache")
public class StudentInfo implements java.io.Serializable {
@Id
@GeneratedValue
@Column(name = "student_id")
private long studentId;
@Column(name = "student_name")
private String studentName;
public StudentInfo() {
}
public StudentInfo(String studentName) {
this.studentName = studentName;
}
public long getStudentId() {
return this.studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return this.studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
Hibernate configuration file is as follows:
hibenate.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">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/testdb</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">*********</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- enable second level cache and query cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>
<mapping class="com.nik.model.StudentInfo" />
</session-factory>
</hibernate-configuration>
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir/ehcache" />
<defaultCache maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" statistics="true">
<persistence strategy="localTempSwap" />
</defaultCache>
<cache name="studentCache" maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="5" timeToLiveSeconds="10">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.internal.StandardQueryCache"
maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
HibernateUtil.java
package com.nik.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
System.err.println("SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
}
StudentServiceImpl.java
package com.nik.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.nik.model.StudentInfo;
import com.nik.util.HibernateUtil;
public class StudentServiceImpl {
public static void main(String[] arg){
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
StudentInfo student = new StudentInfo();
student.setStudentName("Nitesh Sahay");
session.save(student);
session.getTransaction().commit();
StudentInfo stu=(StudentInfo) session.load(StudentInfo.class, 1l);
System.out.println(stu.getStudentName());
session.close();
session = sf.openSession();
session.evict(stu); //evict student from 1st level cache if any
session.clear();//clear 1st level cache
stu=(StudentInfo) session.load(StudentInfo.class, 1l);
System.out.println(stu.getStudentName());
System.out.println(stu.getStudentName());
session.close();
sf.close();
}
}
Output:
No comments:
Post a Comment