Hibernate Second Level Cache Example

Hibernate » on Aug 22, 2011 { 74 Comments } By Sivateja

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 here ]

Files required….

  •  [ Pojo class]
  • Product.hbm.xml
  • ehcache.xml
  • hibernate.cfg.xml

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;

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();

		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.....!!");


		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...!!");

		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.....!!");





<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<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"/>




<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
<property name="connection.url"></property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

<property name="cache.provider_class">

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="">update</property>

<mapping resource="Product.hbm.xml"></mapping>



<?xml version="1.0"?>


<defaultCache maxElementsInMemory="100" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="200" />
<cache name="str.Product" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="200" />


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 —” …….. />



  • From line numbers 1622 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 2731 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 line numbers 3541 we opened second session and loaded the object, this time hibernate will loads the object from the database, and closed the session
  • Immediately from 4349 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

And that’s it mates….!!!!!!!


You Might Also Like

  ::. About the Author .::

Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.


74 Responses to “Hibernate Second Level Cache Example”
  1. Alejandra Gilding says:

    I always was interested in this topic and stock still am, appreciate it for posting.

  2. javaDeveloper says:

    very easy to understand

  3. sudheer says:

    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


  4. Java4s says:

    @Sudheer, @javaDeveloper, @Alejandra Gilding

    Thank you so much friends 🙂

  5. Mahaboob says:

    Really it is vary easy to understand becuse u explined with arrows

    thats good-to-understand-the out-put

  6. Java4s says:


    Glad to hear your feedback on this article 🙂

  7. giri says:

    u r explanation is Fantastic

  8. Java4s says:


    Thank you 🙂

  9. Koushik says:

    Yes..this is the most easiest way to understand 2nd level caching example…. really appreciable

  10. mohanreddy says:

    i am very thankful to you.outstanding explanation, finally the way of showing output console is very good.

  11. Java4s says:

    @Koushik, @MohanReddy

    You welcome friends, glad to hear your feedback on this 🙂

  12. Pavan says:

    this is realy easy to understand …realy nice..way of presentation is good.cover all the small small things.

  13. Very Nice Explanation. Thanks!

  14. Prashanth says:

    Awesome blog!!!! Loved it… Thanks a lot and keep posting various topics on java….

  15. Nagaraj says:

    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…:)

  16. Malathi says:

    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

  17. Java4s says:


    Please read this article, before you execute the example

    We have to store ehcache.xml at class path location.

  18. krish says:


  19. Thabks a lot…This tutorial explains brilliantly and it is easy to understand. You have done a tremendous work. Thank again.

  20. Hats off to this article.

  21. Jamil says:

    Super way to explaining…. Thanks Man.
    You have touched all the point and clear explanation.
    Keep up great job… 🙂

  22. raju says:

    I like it , its really good

  23. Kumar says:

    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.

  24. pradeep381 says:

    How to preLoad few tables during application start up into hibernate cache?

  25. Mahaboob says:

    This is what i am looking for……..

  26. sammy says:

    great way of explanation. Thanks

  27. Hey superb yar. Awesome work done.

  28. Damo says:

    Nice explanation. keep it up.

  29. Ruchi says:

    Excellent Work.. really appreciate your work. keep on posting !

  30. Ashwin says:

    Can You provide me the example of web application using ehcache…?

  31. Anitha says:

    really awesome explanation

  32. anitha says:

    Awesome blog!!!! Loved it… Thanks a lot and keep posting various topics on java….

  33. prasad says:

    please mention where to put the encache.xml file. I mean in which directory/path.

  34. Dibyendu says:

    This is simply great.You have explained so nicely and cleanly.

  35. Sandeep says:

    Can we rename ehCache.xml and then how hibernate reads it??

  36. Ankur says:

    The best way to explain the Hibernate caching…Cheers.!!!

  37. abc says:

    Very simple and easy to understand example. Thanks a bunch!

  38. prabhakar says:

    please write examples using annotations..its more easy to understand

  39. PRahsant says:

    Awesome thanks example

  40. neeraja says:

    Explanation is very nice.

  41. Narasimha says:

    superb blog

  42. Kiruthiga says:

    Very Nice Blog…

  43. Ramakrishna says:

    Nice explaination

  44. Vasu says:

    Hi your website is outstanding, very clear about each and every technology and frameworks of java . i am so impressed about your site. But there is some spelling mistakes is there could please update that one

  45. Aslam says:

    Your blog is very useful…
    Only doubt is …you have not mapped ehcache.xml
    So how ehcache.xml is working …plz explain….


  46. nowik says:

    Thank you for tutorials. They are the best hibernate tutorials i’ve ever read.

  47. Navneet says:

    Hi bro, I am impressed with u. It’s a awesome article. Thanks

  48. Priyank says:

    SO nicely explained, thank you..

  49. Ashish says:

    This is a nice example. I want to apply the same in my web project using struts2. Could you please help me how to achive this?

    Any one has any idea or any link given to me how to use hibernate 4 second lavel catch in web application. I want on server(tomcat) startup all the master data I want to load into cache. further I will get it from cache instead of database.

  50. Pavan Kumar says:

    Very easy to understand, Thank you very much.

  51. Kamalakar says:

    One of the nice tutorial…

  52. anonymous says:

    Good articles. Suggest you to check the spelling and grammar of the content.

  53. Shashanka says:

    Good Explanation Thank you.

  54. Shripad says:

    Thanks a lot.Very excellent explanation.Your way were very easy.

  55. Sarronya says:

    Very descriptive and understandable, thanks much

  56. Rahesh says:

    Excellent !!!. I liked the narration. Thank you very much my friend for explaining this concept so simply.

  57. Manish says:

    Great explanation !!….everything is crystal clear…thanks a lot…keep it up!

  58. Sandip says:

    Helpful for easily and clear understanding in less time.
    Thanks Sivateja.

  59. Manju says:

    Good explanation. understood..

  60. Ram says:

    Best explanation of 2nd level cache Thanks….

  61. Laxmi says:


    Great Explanation.

  62. Sudheer says:

    what is locking system in hibernate?Explain?

  63. Pratibha Sonakneware says:

    Really very nice explanation…..

  64. Srinivas says:

    Good website for learners and developers,
    Just this website is good enough, No need to browse any other tutorials.
    Your explanation is awesome.
    Srinivas Gangam.

  65. Thiru says:

    easy to understand. no other sites can be explained like this. superb

  66. Arun says:

    Really super…Easily I understand…Thank u so much sir…

  67. chandu says:

    very clear explanation..

  68. smd says:

    why u have written timeToIdealSeconds. I thin its idle not ideal.please correct me

  69. smd says:

    Good and clear explanation,its my suggestion to show code on hover on line 16-22.It will be easy and no need to scroll frequently.:)

  70. SHYAM says:

    Splendid explanation Sivateja Kandula.

    Thanks for your help.


By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.