You can view the tutorials best in Google Chrome, Mozilla Firefox, Opera, higher version of Internet Explorer

Hibernate First Level Cache Example

Hibernate » On Aug 10, 2011 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

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 evice() is used to remove a particular object from the cache memory and clear() is to remove all objects in the cache memory

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








By ( Java/J2EE Developer & Web Designer )
Founder of Java4s.com. You can contact me at sivateja [at] java4s.com


Comments

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

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

  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 ?

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
So, What would you like to learn today?
Browse these popular technologies
Hibernate spring struts Servlets ajax Log4j jQuery Json Core Java Web Services AngularJs

Most Recent Tutorials
Hibernate Recent Posts
Spring Recent Posts
Struts Recent Posts
Recomandded Links
Current & UpComing Tutorials
Sitemap :
spring Hibernate struts Json Ajax Log4j Log4j coreJava Servlets Web Services


Upcoming
  Web Services [ SOAP ], JSP
Facebook_Java4s  Twitter_Java4s  GooglePlus_Java4s  Youtube_Java4s 
© 2010 - 2014 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.