Hibernate Cache - Gary's Edition

January 8, 2010 - 3:35pm
Submitted by gary

Hibernate Cache - I will quickly write a simplified version of all the hibernate cache jargons that you can find on the net.

 

Caching: is to put objects in memory so we can access these information quickly.


Hibernate has 2 types of cache:

1st level cache: The process of Hibernate storing all the object changes in memory during a transaction without actually commiting is called the 1st lvl cache.

    For Example: Assume you have object Car mapped to table car, and Driver mapped to driver table in your database.

                           So you want to do the following: Find Cars that are yellow, Change Car color to red, Get Driver named "Gary" in database, assign these cars to this driver. (one to many, many to many, doesn't matter). All that is wrapped in one transaction.

                           Then Hibernate will cache every step, and only do a one time commit to the database at the end of the transaction.

                           This is good when something goes wrong and you want to roll back your changes.

 

2nd level cache: This is the actual objects Hibernate stores in memory for easy access.

    For Example: Let say you did call to get all cars that are yellow, then did a call to get all drivers that have red cars.

                            Once those calls are done, the objects are not deleted, but instead stored in memory.

                            So when someone does a call to get cars that are yellow, or drivers that have red cars, Hibernate will return the objects stored in cache instead of going to the database and get a fresh copy. This increases query speed greatly.

       Just imagine 90% of the users in your application queries cars that are yellow. Hibernate will return the query with blazing speed.

 

There are many types of cache implementations for Hibernate, but I wont go into it here, since the important part is to understand WHAT Hibernate is really doing behind the scene