Newsletter

Hibernate First Level Cache Example

Hibernate » on Aug 10, 2011 { 43 Comments } By Sivateja

Let us try to understand the first level cache in hibernate,  actually i tried to give almost all the concept about this first level cache hope you will enjoy this 🙂

  • By default, for each hibernate application, the first level cache is automatically been enabled
  • As a programmer, we no need to have any settings to enable the first level cache and also we cannot disable this first level cache
  • the first level cache is associated with the session object and scope of the cache is limited to one session only
  • When we load an object for the first time from the database then the object will be loaded from the database and the loaded object will be stored in the cache memory maintained by that session object
  • If we load the same object once again, with in the same session, then the object will be loaded from the local cache memory not from the database
  • If we load the same object by opening other session then again the object will loads from the database and the loaded object will be stored in the cache memory maintained by this new session

 

 Example

Session ses1 = factory.openSession();
Object ob1 = ses1.get(Student.class, new Integer(101));

Object ob2 = ses1.get(Student.class, new Integer(101));
Object ob3 = ses1.get(Student.class, new Integer(101));
Object ob4 = ses1.get(Student.class, new Integer(101));

--
session.close();

Session ses2 = factory.openSession();
Object ob5 = ses2.get(Student.class, new Integer(101));

Explanation:

  • In line number1, i have opened one session with object is ses1
  • In line number2, loaded one object with id 101, now it will loads the object from the database only as its the first time, and keeps this object in the session cache
  • See at line number 4,5,6 i tried to load the same object 3 times, but here the object will be loaded from the stored cache only not from the database, as we are in the same session
  • In line number 9, we close the first session, so the cache memory related this session also will be destroyed
  • See line number 11, again i created one new session and loaded the same object with id 101 in line number 12, but this time hibernate will loads the object from the database

Finally what am trying to tell you is…

x . number of sessions = that many number of cache memories

 

Important

The loaded objects will be stored in cache memory maintained by a session object and if we want to remove the objects that are stored in the cache memory,  then we need to call either evict() or clear() methods.   Actually evict() is used to remove a particular object from the cache memory and clear() is to remove all objects in the cache memory

>Session ses = factory.openSession();
Object ob = ses1.get(Student.class, new Integer(101));
Student s = (Student)ob
System.out.println(s.getStudentId());

ses.evict(s);

Object ob1 = ses.get(Student.class, new Integer(101));
  • Opened session at line number 1
  • Loaded the object with id 101, so hibernate will lads this object from the database as this is the first time in the session
  • At line number 4, i printed my data  bla bla..
  • then in line number 6, i removed this object [ with id 101 ] from the cache memory of the session by calling evict() method
  • Now in line number 8 again i tried to load the same object,  so as we are in the same session hibernate first will verify whether the object is there in the cache or not, if not loads the object from the database, but we removed the object from the cache with evict() method right, so hibernate will loads from the database
  • I mean, first checks at local session then only from the database if its not available in the local cache

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

​​

You Might Also Like

  ::. About the Author .::

Java4s_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.

Comments

43 Responses to “Hibernate First Level Cache Example”
  1. Naveen Kumar says:

    Hi,

    I have a question on first level caching

    Below is the same code

    Session ses = factory.openSession();
    Object ob = ses.get(Student.class, new Integer(101));
    Student s = (Student)ob
    System.out.println(s.getStudentId());
    Object ob = ses.get(Person.class, new Integer(101));
    Person p = (Person)ob
    System.out.println(p.getPerson());

    ses.clear();

    }
    }
    What will happen if i do like this…

    Whether we save same table object in the session cache or we can save two differnt table objects in the same session.

    Here my question is “whether a session cache can hold two different table objects in the same cache or not?”

    Thanks,
    Naveen.

  2. Java4s says:

    Hi Naveen,

    yes we can load the objects of 2 different tables with same id in a single session.
    But while typecasting you must take separate object [ You are using ob for both objects ]

    Would be fine if you re-write like

    Session ses = factory.openSession();
    Object ob = ses.get(Student.class, new Integer(101));
    Student s = (Student)ob
    System.out.println(s.getStudentId());
    Object ob1 = ses.get(Person.class, new Integer(101));
    Person p = (Person)ob
    System.out.println(p.getPerson());

    Hope you are clear

  3. Naveen Kumar says:

    Hi,

    Thanks for your reply,

    I have one more doubt.
    Suppose if i call ses.clear()will it remove all objects from the cache.ie., Student object 101,Person object 101.Here object means one row in database am i right.
    Also one thing while loading two different objects in same session i need to pass same id as you said for the earier reply.What will happen if i pass different id’s for Student and Person.I think you got my point.

    Session ses = factory.openSession();
    Object ob = ses.get(Student.class, new Integer(101));
    Student s = (Student)ob
    System.out.println(s.getStudentId());
    Object ob1 = ses.get(Person.class, new Integer(102));
    Person p = (Person)ob1
    System.out.println(p.getPerson());

    Thanks,
    Naveen.

  4. java4s says:

    @Naveen

    yeah, if you close the session all objects associated with that session will be removed.

    Yeah in hiberante, 1 object = 1 row in the database table.

    Yeah you can call objects with different ids too, its your choice.

    • Karthika Srinivasan says:

      Hello Sir, I have a doubt. For the first the object its said that it will be fetched from Database. Is that entire table(Student) data is loaded in cache? Because you told like for the next subsequent calls with the same loads object from cache.

    • Khagesh says:

      Hi java4s,

      If i call object with different id's then for every id, it will call database for example if i use id 1 then it will hit first time, if i use id 2 then it will hit second time…

  5. Naveen Kumar says:

    Hi,

    Is there any limit in storing objects in session cache or session factory cache and what query cache?

    Also, What is the differnce b/w load(Class clazz,Serializable id) and load(Object object,Serializable id)? Why we have these two variants.

    Thanks,
    Naveen.

  6. Java4s says:

    @Naveen

    I guess, your question is regarding

    — load(Class theClass, Serializable id)
    — load(Object object, Serializable id)

    if so…

    Thing is, First method return type is Object class object [ Which is most super class of all java classes ], and actually this is always recommended approach. Typecasting into most super class is always preferable rather typecasting into particular class, hope you know this fundamental.

    Example:
    Object o = session.load(Product.class,new Integer(100));
    Product p = (Product)o;
    — Now print the values —

    And Second method will returns void, and we can pass directly our POJO class object as first parameter, but its not recommended approach. What i mean to say is depends on the situations we can..

    Example:
    Product p = new Product();
    session.load(p, new Integer(100);
    — Now print the values —

    But first approach i saw mostly in real time.

  7. Mohammed Vaseem says:

    What is the difference between session.get() and session.load()?
    Where and when which method is used?
    Thanks in advance..

  8. Mohammed Vaseem says:

    When the value which we want to fetch, suppose new Integer(100) is not available in the database, then it is throwing null pointer exception. So how to manage control in safe hands..
    Thanks in advance.

  9. karthikeyan Ganapathy says:

    Its a very good question and answer is excellent, hats off Java4s

  10. Sheshankit Dash says:

    A very good example and discussion of First level caching

  11. Java4s says:

    @ Karthikeyan Ganapathy, @ Sheshankit Dash

    Thanks for your feedback friends.

  12. Java4s says:

    @ Mohammed Vaseem

    The load() method is older one,
    get() was added into Hibernate’s API due to user request. If load() can’t find the object in the cache or database, exception will be thrown. This load() method never returns null.

    But get() method returns null if the object can’t be found.

    session.load() will always return a “proxy” without hitting the database. Session.get() always hit the database and returns original object.

  13. brahmaiah says:

    Hi,

    how should we disable first level cache in hibernate?

    Thanks,
    Brahmaiah

  14. Java4s says:

    @Brahmaiah

    As i mentioned in the article, First level cache is associated with the session object, cache will be destroyed once we destroy the session object.

  15. very good explanation about first level cache. great works java4s 🙂

    @java4s
    can u please tell, when or in which version get() was added into Hibernate’s API??

  16. Mahammad says:

    What is transaction management in hibernate?

    can you please explain.

  17. nagaraju says:

    1) what is the difference b/w merge and update?
    2) i used session.merge(obj),is it added to first level cache?

  18. Java4s says:

    @nagaraju

    you can find the difference between merge and update here … !

  19. sam2013 says:

    Hi,

    What i understand from the caching mechanisam is objects gets temporary place in cache memory of our computer syste.
    If there are thousand or lacks of objects takes place in cache memory then how it impacts performance of our system(or whether it really affects computer’s performance)?

  20. Murali says:

    Hi,
    Very good explanation.
    I have a query regarding caching. I have an object loaded from database and it will be cached and subsequent load it will be retrieved from cache. What happens if my database updated same object by other resource? will i get cached object or updated object from database?

  21. dinesh says:

    What is session expiry and what is the session memory size, how many object can it hold???????

  22. Mariappan says:

    What happens if we do like this,

    Session ses1 = factory.openSession();
    Object ob1 = ses1.get(Student.class, new Integer(101));
    Object ob2 = ses1.get(Student.class, new Integer(101));

    String hql_update = “UPDATE Student st SET st.name= ‘AAA’ WHERE id =101”;
    ses1.createQuery(hql_update);

    Object ob3 = ses1.get(Student.class, new Integer(101));
    Object ob4 = ses1.get(Student.class, new Integer(101));


    session.close();

    1) Whether ob3 and ob4 gets the updated value..??

    2) Whether ob3 and ob4 gets it’s value from cache or it hits the database..??

    • narender reddy says:

      no it won't updated the value ob3 and ob4 loaded from cache only. you need call session.evict() to clear cache of Student object.then you need to update the value

  23. Nirav says:

    Dear Mariappan ,

    1 ) No , ob3 and ob4 will not get updated value
    2 ) because you haven’t performed session close() or session clear() function . so ob3 & ob4 lines will not hit database , it will directly fetch data from first level cache.
    3 ) To get updated value , put ses1.clear() function , so that ob3 line will hit the database.

  24. prasad66 says:

    Hi,

    What i understand from the caching mechanism is objects gets from Persistent context?

    If there are thousand or lacks of objects takes place in cache memory then how it impacts performance of our system(or whether it really affects computer’s performance) and what is maximum size hold in Cache and do we need mention cache size limit anywhere in configuration file ?

  25. Vishal says:

    This Code is not removing the object from memory,And i am getting the Name of Employee.

    Configuration cfg=new Configuration();
    cfg.configure(“hibernate.cfg.xml”);

    SessionFactory factory =cfg.buildSessionFactory();
    Session s1=factory.openSession();

    Object o=s1.get(Employee.class,new Integer(3));

    s1.clear();
    s1.evict(o);
    s1.close();

    Employee e=(Employee) o;
    System.out.println(e.getFirstName());

    System.out.println(“Name of Employee”);

  26. Chetan says:

    Awesome Tutorial i found here.
    Please update you mistake typed evice in place of evict………..please update it may be other user will be confused.

  27. Java4s says:

    @Chetan

    Thank you, I have updated the code 🙂

  28. samba says:

    Hi,
    in level-one caching contains 101,102,103. i tried to delete 106 using evict(). but 106 is not there in my cache.wat happend?

  29. Priyank says:

    Very good explanation.

  30. Bhushan says:

    Hi Siva,
    As you gave explanation about load 2 different table in same cache , you told we can load 2 different table with same id , can we load 2 different table with different id?

  31. Ashish says:

    As you explained:

    session.load() will always return a “proxy” without hitting the database. Session.get() always hit the database and returns original object.

    But in the example you have mentioned that Session.get() then how we are achieving first level cache here because “Session.get()” always hit the database and returns original object.

  32. Ravi Sankar says:

    Excellent Explanation on most important things !!!

    I found One Important information missing …

    Assume some value is present in Hibernate cache and someone updates value in the DB without Hibernate (assume from mysql console) … then what will happen to the value present in Hibernate cache?

    :If there is any database update with Hibernate, then, Hibernate will automatically invalidate/trash the cached content, but if some other process updates the value on DB (that is present in hibernate cache), then Hibernate never knows it is modified and Hibernate continue to hold the stale object value

  33. Swathi says:

    I found good site today, nice explanation……!!!
    Thanx alot…!!

  34. vamsi says:

    I got this question in interview.. Who will put the objects in cache.

  35. arvind says:

    Sir in my program session1’s cache stored value then loads in every calling with different objects of same pojo right. but I created second session say session2 without closing session1 and updated database’s row (whose values are currently in cache of session1) then again i called same row by pojo of session1 then it views updated value ! so what about cache of session1?

  36. arvind says:

    Object o1=session1.get(Product.class, new Integer(1));
    Object o2=session1.get(Product.class, new Integer(1));
    Object o3=session1.get(Product.class, new Integer(1));
    Product pr1=(Product)o1;
    Product pr2=(Product)o2;
    Product pr3=(Product)o3;

    // from object o1
    System.out.println(“first retrive:(from object o1) “+pr1.getProId());
    System.out.println(“first retrive: “+pr1.getProname());
    System.out.println(“first retrive: “+pr1.getProprice());
    Transaction tx=session1.beginTransaction();
    SessionFactory factory2 = cfg.buildSessionFactory();
    Session session2=factory2.openSession();
    Product pr6=(Product)o2;
    pr6.setProname(“BETA”);
    session2.update(pr1);
    tx.commit();
    session2.close();

    // from object o2
    System.out.println(“second retrive:(from object o2 of session1) \n”+pr2.getProId());
    System.out.println(“second retrive:( of session1) \n”+pr2.getProname());
    System.out.println(“second retrive:( of session1) \n”+pr2.getProprice());
    —- Sir why o2 of session1 represend values from database na dnot fron sesion1’s cache?

  37. Fazeela says:

    Nice tutorial

  38. kajal says:

    Really very useful & easily understandable.

  39. Narendra Kumar says:

    Really nice tutorial

  40. Manisha says:

    Hello,

    Session ses1 = factory.openSession();
    Object ob1 = ses1.get(Student.class, new Integer(101));

    Object ob2 = ses1.get(Student.class, new Integer(101));
    ses1. Clear() ;
    system. out. println(ob2.getName()) ;
    Object ob3 = ses1.get(Student.class, new Integer(101));
    Object ob4 = ses1.get(Student.Session ses1 = factory.openSession();


    session.close() ;

    Please explain me when i load ob2 and after that i did call ses1. clear() method… Now ses1 is clear mean in ses1 cache memory is empty..
    am i right… Now
    When i print
    system. out. println(ob2.getName()) ;
    It prints value… But cache is empty then how it can print the value of name..

Name*
Mail*
Website



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.