The first-level cache is the Session cache and is a mandatory cache through which all requests must pass. The Session object keeps an object under its own power before committing it to the database.For how many sessions we are creating, it is maintain a session area in memory called session cache.
Insert operation: when you are inserting the data, and updating the same data in DB. then, it will not directly insert the data in the DB,What it will do. Hibernate intelligently identifies that, same data is updating. ,and last update will be triggered to the Database.
Limitation of First level Cache:
Once you close the session, the cache will get destroyed.
For ex: when we use select * from customer, and close the session, then it will again hit the DB.So to overcome this problem, we use Second Level Cache.
By default first level is enabled, in our code, we as a java developer don't enable/disable it forcefully in our code.
First level cache will be enabled by default, but for enable second level cache we need to follow some settings, let us see few points regarding this..
Second level cache was introduced in hibernate 3.0
When ever we are loading any object from the database, then hibernate verify whether that object is available in the local cache memory of that particular session [ means first level cache ], if not available then hibernate verify whether the object is available in global cache or factory cache [ second level cache ], if not available then hibernate will hit the database and loads the object from there, and then first stores in the local cache of the session [ first level ] then in the global cache [ second level cache ]
When another session need to load the same object from the database, then hibernate copies that object from global cache [ second level cache ] into the local cache of this new session
Second level cache in the hibernate is of from 4 vendors…
We need one provider class, here we are going to see hibernate provider class that is EHCache
How to enable second level cache in hibernate
To enable second level cache in the hibernate, then the following 3 changes are required
1. Add provider class in hibernate configuration file (hibernate.cfg.xml )
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
2. Configure cache element for a class in hibernate mapping file (hbm file )
<cache usage="read-only" />
3. Create ehcache.xml file
<?xml version="1.0"?>
<ehcache>
<cache name="testCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="10"
overflowToDisk="true"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="120"
maxElementsOnDisk="10000"
/>
</ehcache>