Saturday, February 8, 2014

Understanding hibernate first level cache with example

Caching is a facility provided by ORM frameworks which help users to get fast running web application, while help framework itself to reduce number of queries made to database in a single transaction. Hibernate achieves the second goal by implementing first level cache.
Fist level cache in hibernate is enabled by default and you do not need to do anything to get this functionality working. In fact, you can not disable it even forcefully.
Its easy to understand the first level cache if we understand the fact that it is associated with Session object. As we know session object is created on demand from session factory and it is lost, once the session is closed. Similarly, first level cache associated with session object is available only till session object is live. It is available to session object only and is not accessible to any other session object in any other part of application.
Hibernate first level cache
Hibernate first level cache

Important facts

  1. First level cache is associated with “session” object and other session objects in application can not see it.
  2. The scope of cache objects is of session. Once session is closed, cached objects are gone forever.
  3. First level cache is enabled by default and you can not disable it.
  4. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session.
  5. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed.
  6. The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method.
  7. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.
Lets verify above facts using examples.

First level cache retrieval example

In this example, I am retrieving DepartmentEntity object from database using hibernate session. I will retrieve it multiple times, and will observe the sql logs to see the differences.
//Open the hibernate session
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

//fetch the department entity from database first time
DepartmentEntity department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1));
System.out.println(department.getName());

//fetch the department entity again
department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1));
System.out.println(department.getName());

session.getTransaction().commit();
HibernateUtil.shutdown();

Output:

Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
Human Resource
Human Resource
As you can see that second “session.load()” statement does not execute select query again and load the department entity directly.

First level cache retrieval example with new session

With new session, entity is fetched from database again irrespective of it is already present in any other session in application.
//Open the hibernate session
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

Session sessionTemp = HibernateUtil.getSessionFactory().openSession();
sessionTemp.beginTransaction();
try
{
 //fetch the department entity from database first time
 DepartmentEntity department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1));
 System.out.println(department.getName());
 
 //fetch the department entity again
 department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1));
 System.out.println(department.getName());
 
 department = (DepartmentEntity) sessionTemp.load(DepartmentEntity.class, new Integer(1));
 System.out.println(department.getName());
}
finally
{
 session.getTransaction().commit();
 HibernateUtil.shutdown();
 
 sessionTemp.getTransaction().commit();
 HibernateUtil.shutdown();
}

Output:

Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
Human Resource
Human Resource

Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
Human Resource
You can see that even if the department entity was stored in “session” object, still another database query was executed when we use another session object “sessionTemp”.

Removing cache objects from first level cache example

Though we can not disable the first level cache in hibernate, but we can certainly remove some of objects from it when needed. This is done using two methods :
  • evict()
  • clear()
Here evict() is used to remove a particular object from cache associated with session, and clear() method is used to remove all cached objects associated with session. So they are essentially like remove one and remove all.
//Open the hibernate session
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
try
{
 //fetch the department entity from database first time
 DepartmentEntity department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1));
 System.out.println(department.getName());
 
 //fetch the department entity again
 department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1));
 System.out.println(department.getName());
 
 session.evict(department);
 //session.clear(); 
 
 department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1));
 System.out.println(department.getName());
}
finally
{
 session.getTransaction().commit();
 HibernateUtil.shutdown();
}
  
Output:
  
Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
Human Resource
Human Resource

Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=?
Human Resource
Clearly, evict() method removed the department object from cache so that it was fetched again from database.
Hope you likes above article. If you got any question or suggestion, drop a comment.
Happy Learning !!

6 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

Zheng junxai5 said...

zhengjx20160721
kd 7 shoes
gucci outlet online
air jordan shoes
vans outlet
gucci outlet
coach outlet clearance
louis vuitton handbags
nike roshe run mens
concords 11
cheap jordans
nike air force 1 white
oakley sunglasses
michael kors outlet clearance
air jordan shoes
louis vuitton outlet stores
true religion jeans
louis vuitton
louis vuitton handbags
nike store
lebron 12
ralph lauren
timberlands
polo ralph lauren
louis vuitton purses
christian louboutin outlet
nike store uk
coach outlet online
mont blanc pen
nike air max 90
michael kors outlet
adidas originals store
oakley vault
tods outlet store
cheap oakleys
true religion jeans
discount jordans
true religion outlet store
michael kors outlet
kobe 10
asics shoes for men

raybanoutlet001 said...

fitflops sale
cheap air jordans
huarache shoes
nike huarache sale
cheap jordans
air jordan shoes
michael kors handbags
cheap jordans online
michael kors outlet
michael kors outlet
nike huarache
michael kors handbags,michael kors handbags clearance,michael kors clearance
nfl jerseys from china
true religion store
nmd adidas store
air jordan shoes
adidas yeezy boost
michael kors outlet online
http://www.outlettiffanyand.co
tiffany and co outlet
adidas stan smith
tiffany jewelry
http://www.oakleystoreonline.us.org
ugg outlet