Hibernate Second Level Cache Example
|
Hibernate »
On Aug 22, 2011 | { 28 Comments }
|
Tweet
|
Let us see the example on this hibernate second level cache. please go through the concept on this second level cache, still if you have any doubt [ Click hear ]
Files required….
- Product.java [ Pojo class]
- ForOurLogic.java
- Product.hbm.xml
- ehcache.xml
- hibernate.cfg.xml
Product.java
package str;
public class Product{
private int productId;
private String proName;
private double price;
public void setProductId(int productId)
{
this.productId = productId;
}
public int getProductId()
{
return productId;
}
public void setProName(String proName)
{
this.proName = proName;
}
public String getProName()
{
return proName;
}
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}
}
ForOurLogic.java
package str;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ForOurLogic {
public static void main(String[] args)
{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession();
Object o=session1.load(Product.class,new Integer(105));
Product s=(Product)o;
System.out.println("Loaded object product name is___"+s.getProName());
System.out.println("Object Loaded successfully.....!!");
session1.close();
System.out.println("------------------------------");
System.out.println("Waiting......");
try{
Thread.sleep(6000);
}
catch (Exception e) {
}
System.out.println("6 seconds compelted......!!!!!!!!");
Session session2 = factory.openSession();
Object o2=session2.load(Product.class,new Integer(105));
Product s2=(Product)o2;
System.out.println("Loaded object product name is___"+s2.getProName());
System.out.println("Object loaded from the database...!!");
session2.close();
Session session3 = factory.openSession();
Object o3=session3.load(Product.class,new Integer(105));
Product s3=(Product)o3;
System.out.println("Loaded object product name is___"+s3.getProName());
System.out.println("Object loaded from global cache successfully.....!!");
session3.close();
factory.close();
}
}
Product.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="str.Product" table="products"> <cache usage="read-only" /> <id name="productId" column="pid" /> <property name="proName" column="pname" length="10"/> <property name="price"/> </class> </hibernate-mapping>
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"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver </property> <property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">admin</property> <property name="cache.provider_class"> org.hibernate.cache.EhCacheProvider </property> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="Product.hbm.xml"></mapping> </session-factory> </hibernate-configuration>
ehcache.xml
<?xml version="1.0"?> <ehcache> <defaultCache maxElementsInMemory="100" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="200" /> <cache name="str.Product" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="200" /> </ehcache>
Regarding ehcache.xml
- In ehcache.xml, if eternal=”true” then we should not write timeToIdealSeconds, timeToLiveSeconds, hibernate will take care about those values
- So if you want to give values manually better eternal=”false” always, so that we can assign values into timeToIdealSeconds, timeToLiveSeconds manually, and play
- timeToIdealSeconds=”seconds” means, if the object in the global chche is ideal, means not using by any other class or object then it will be waited for some time we specified and deleted from the global cache if time is exceeds more than timeToIdealSeconds value
- timeToLiveSeconds=”seconds” means, the other Session or class using this object or not, i mean may be it is using by other sessions or may not, what ever the situation might be, once it competed the time specified timeToLiveSeconds, then it will be removed from the global cache by hibernate
- Actually <defaultCache … /> will reflects to all the pojo classes in our application, and we can also assign the ehcache values to specified pojo class by <cache name=”– your pojo class name —” …….. />
Regarding ForOurLogic.java
- From line numbers 16 – 22 we opened session1 and loaded object and closed session1, this time object will be loaded from the database as its the first time
- Then from 27 – 31 we have been waited for 6 seconds, but in our ehcache.xml we have given timeToIdleSeconds=”5″ , i mean after 5 seconds object will be removed from the global cache
- And again in ForOurLogic.java line numbers 35 – 41 we opened second session and loaded the object, this time hibernate will loads the object from the database, and closed the session
- Immediately from 43 – 49 we opened session3 and loaded the object, this time hibernate will loads the object form the global session not from the database
We have existing record in the database
![]() |
![]() |
Output after run the ForOurLogic.java
![]() |
![]() |
And that’s it mates….!!!!!!!
|
What you are thinkig....
28 Responses to “Hibernate Second Level Cache Example”
If you want a pic to show with your comment, go get a gravatar !
Please post your questions on Java4s Answers forum





I always was interested in this topic and stock still am, appreciate it for posting.
very easy to understand
man,
your articles are just outstanding. I will tell you the author even can’t explain so clearly and crystal clear on any concepts. they are just easy to learn and covering every concept in a very simple way.
Keep it up…
This is a outstanding blog i had come across till now
bye
raj
@Sudheer, @javaDeveloper, @Alejandra Gilding
Thank you so much friends
Really it is vary easy to understand becuse u explined with arrows
thats good-to-understand-the out-put
@Mahaboob
Glad to hear your feedback on this article
u r explanation is Fantastic
@giri
Thank you
Yes..this is the most easiest way to understand 2nd level caching example…. really appreciable
i am very thankful to you.outstanding explanation, finally the way of showing output console is very good.
@Koushik, @MohanReddy
You welcome friends, glad to hear your feedback on this
this is realy easy to understand …realy nice..way of presentation is good.cover all the small small things.
Very Nice Explanation. Thanks!
Awesome blog!!!! Loved it… Thanks a lot and keep posting various topics on java….
Awesome man:) i heard about another cache called Query cache,can you provide explanation to it? Have you ever posted on Struts or struts with hibernate configuration?if yes please provide me a link….Thanks a lot,will follow your posts…:)
@Nagaraj
Will post query cache too, here is Struts 2 Hibernate Integration Example…
http://www.java4s.com/struts-tutorials/struts-2-hibernate-integration-example-struts-2-hibernate-integration/
Hey i wanted to know where to store thie ehcache.xml and how is it called in the application.. Thanks in advance. Ur explanations are crystal clear
@Malathi
Please read this article, before you execute the example
http://www.java4s.com/hibernate/how-to-enable-second-level-caching-in-hibernate/
We have to store ehcache.xml at class path location.
Super……Explanation…Super…………..
Thabks a lot…This tutorial explains brilliantly and it is easy to understand. You have done a tremendous work. Thank again.
superb…
Hats off to this article.
Super way to explaining…. Thanks Man.
You have touched all the point and clear explanation.
Keep up great job…
I like it , its really good
Thank you boss
This example for only 1 project, what will be if having more than 1 project in my workspace. How i am going to write ehcache.xml file, to saparate the diskStore path.
Hi,
How to preLoad few tables during application start up into hibernate cache?
This is what i am looking for……..