Hibernate provides us with three caching mechanism:
1. First Level Cache
2. Second Level Cache
3. Query Cache
First Level Cache is the 'Session' object in Hibernate. It is a mandatory cache and the Session takes care of managing the Entity objects inside it.
Hibernate doesn't trigger multiple update statement and hits the database. But if there are multiple update statements in a session, Hibernate only triggers the last update statement. All this are managed inside the Session or First Level Cache.
There are instances when the First Level Cache is unable to handle some critical scenarios. In such cases Second Level Cache comes into picture.
It needs to be configured and there are few cache Providers listed below:
- EHCache
- OSCache
- JBoss Cache
We will be taking the example of EHCache and explain how 'Second Level Cache' works.
Below are the steps to download and setup the EHCache:
1. Go to the download folder where you have downloaded the Hibernate zip file. Then go to the path hibernate-release-4.2.3.Final/lib/optional/ehcache 2. Take all the jar files from the above location and place them along with other jars in your project. 3. Now, in 'Hibernate.cfg.xml', enable the second level cache and set the necessary properties for 'EHCache'.
4. In the Employee.hbm.xml mapping file, set the EHCache using the '<cache >' tag.