Wednesday, October 5, 2016

First Level Cache in Hibernate

Caching is a mechanism for storing the loaded objects into cache memory. The advantage of this is, whenever we want to load the same object from the database, instead of hitting the database once again, it loads from the local cache memory, so that the no. of round trips between an application and the database gets reduced.

Caching mechanism increases the performance of the application.

In hibernate we have two levels of caching
First Level Cache [Session Cache]
Second Level Cache [Session Factory Cache or JVM Level Cache]


By default, for each hibernate application, the first level cache is automatically enabled and we cannot disable it.

First level cache is associated with the session and its scope is limited to one session only.

When we load an object for the first time from the database, the object gets loaded from the database and stored in the cache memory.

If we load the same object once again in the same session, then the object will be loaded from the local cache memory instead of the database.

If we load the same object by opening another session, then again the object will be loaded from the database and stored in the cache memory of this new session.

Example:
1)Session session1 = factory.openSession();
2)Object obj1 = session1.get(Emp.class, new Integer(101));

3)Object obj2 = session1.get(Emp.class, new Integer(101));
4)Object obj3 = session1.get(Emp.class, new Integer(101));

5)session.close();

6)Session session2 = factory.openSession();
7)Object obj4 = session2.get(Emp.class, new Integer(101)); 

In the above example, object will be loaded from the database at line number 2.

But at line number 3 and 4 it will be loaded from the cache.

Again at line number 7 object is loaded from the database since its a new session.

No comments:

Post a Comment

Home