Session Level Cache or Level 1 Cache in Hibernate.

Cache is a buffer/temporary memory allocated in RAM. Caching is a mechanism which reduces database interactions and improves the performance of an Application. In Hibernate a Cache is manage by two objects:-

– Session Object.
– SessionFactory Object.


A cache managed by Session object is called a Level 1 Cache or Local Cache. A Cache managed by Factory is called Level 2 Cache or global Cache.
Level 1 Cache will be automatically created by Hibernate, when a Session is opened and it will be automatically closed when session is closed. As a programmer we no need to add any special tags in a .hbm file or in a .cfg file. This Level 1 Cache is not in hands of a programmer, it is in the hands of hibernate only. Each session will have its own Cache. A session can not read object from another session cache. As a programmer, we can delete either a specific object or all objects from cache, but we can not delete the cache. To delete a specific object, we can call evict() method and to delete all object from cache, we can call clear() method. When we call evict() method, if the id of an object does not exist in cache then evict() method throws an Exception. So, before evicting, we can check whether an object exist in cache or not with the help of contains() method.
e.g;
if(session.contains(obj)){
session.evict(obj);
}

A problem with cache is, if an object is updated in database then the changes are not automatically reflected on cache. It is a programmer responsibility to refresh a cache at regular intervals, to get the changes from database to the cache.
e.g;
Object o1 = session.get(Product.class, 101);
Object o2 = session.get(Product.class, 101);
session.evict(o1);
Object o3 = session.get(Product.class, 101);
Object o4 = session2.get(Product.class, 101);

For the above code totally three selects are generated by Hibernate.

One thought on “Session Level Cache or Level 1 Cache in Hibernate.”

Leave a Reply

Your email address will not be published. Required fields are marked *