What is Caching?
Caching is a process of saving data into the cache memory. A cache is a temporary storage layer which is used to increase the speed of data access. It allows us to reuse the data stored in the cache memory to improve data retrieval.
What is Hibernate caching?
Hibernate ORM framework provides a caching facility which is used to get fast running applications, by reducing the number of queries (SQL and Native HQL) in the database. In other words, it improves the performance of the application by uniting the object in the cache memory. It helps in retrieving the same data multiple times.
There are three types of caching:–
- First Level Cache
- Second Level Cache
- Query Cache
First Level Cache
The first-level cache is related to the Session object. It is mandatory cache as all the requests made in the application passed through it. It is enabled by default, and we can’t disable it. Scope of first level cache is of the Session that means it is not available to the entire application.
There are some essential methods used in the first-level cache. They are listed below-
- evict()- It is used to remove the loaded object from a first-level cache.
- clear()- It is used to remove all the objects stored in the first-level cache.
- contains()- It is used to check an object is present in the cache or not. If the object is found, it returns true else false.
Second Level Cache
The second-level cache is related to the SessionFactory object, and it is optional. Scope of the second-level cache is global, that means it is available to the entire application. Unlike the first-level cache, it is not enabled by default. So, we need to enable it explicitly.
When a user retrieves data from the database for the first time, the data gets stored in the second-level cache (if enabled for that object).
Hibernate also provides a cache for a query result set that links with the second-level cache. It is useful for the queries that run regularly.by