Hibernate being one of the most preferred and popular ORM frameworks today, provides a very crucial feature alongside, which is caching.
Types of caching
There are two types of caching provided by Hibernate –
- First level cache
- Second level cache
First level cache is enabled by default for the current session.
Second level cache is not enabled by default and is available at the sessionFactory level, so the cached data is globally available to all the sessions created using the same sessionFactory object in the application. The second level cache needs to be enabled explicitly, which we will see when we integrate ehCache as the second level cache in our application.
So once the sessionFactory is closed, all the session data gets cleared out.
There are different vendors that provide the implementation of the Hibernate second level cache. To list the most popular ones are –
- EH Cache
- Swarm Cache
- OS Cache
- JBoss Cache
How does the second level cache work?
- Whenever we load an entity in Hibernate, the cached copy of the entity is searched in the first level cache of the current session.
- If the entity is found in the first level cache, it is returned successfully.
- If the entity is not found in the first level cache, the entity is searched in the second level cache.
- If the entity is found in the second level cache, the entity is returned as a result of load method, while storing the entity into the first level cache as well, for a better performance in the subsequent calls.
- If not found in the second level cache too, the database query is executed, and the loaded entity is cached at both first and the second level.
Alternatively, we can invalidate the second level cache explicitly as –