Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Caching in Hibernate: Session Cache

Cache:  Caching is used for reducing the number of interactions with the database. If there is no cache then for every interaction application has to hit the database.

   Cache contains the data which is already loaded from database and hits the database when data is updated.


Session Cache in Hibernate can be designed for per transaction basis.For example under one transaction if obj1 is saved then modifications can be updated in  cache, obj 2 is deleted again modifications are updated in cache and if we undo obj1's modifications it can be undo-ed from cache.For all these modifications our application cannot touch database until the transaction has been completed, in the above example saving and undoing the save wont touch the database hence our application performance will increases.

A Session cache caches objects in the current session.Fetching an object from database always expensive.So when ever new object fetched from database, store that in session's cache, next time when it requires pick it from cache rather than from database.

Session cache enabled by default.Let us suppose we create two queries for loading project object.

    session.createQuery("from Project where pid=1");

when first time the query executes application loads the data from database.

Again if we execute the same query     session.createQuery("from Project where pid=1"); we expect that the object should be retrieved from cache but it should n't happen with executing queries, application again fetches the object from database. For clarification on this issue go through Query Cache concept.

Contrary to this if we execute    session.load("Project",1);    For first execution it retrieve the data from database and keep the object in session cache, for the second execution it retrieves the data from cache because objects are already stored in cache.

If we load the objects through get(),load() methods then only  the retrieved objects can be stored in session's cache, if we retrieve the objects through query then those objects are not stored in session's cache, those are stored in query cache we will discuss query cache later.

                                                                                                                  Vissu

  


This post first appeared on Java Spring Hibernate, please read the originial post: here

Share the post

Caching in Hibernate: Session Cache

×

Subscribe to Java Spring Hibernate

Get updates delivered right to your inbox!

Thank you for your subscription

×