caching is the facility of storing object temporally in the memory . The purpose of caching to improve the performance by reducing database hits . If same object is required by different session or user then it make sense to fetch them only one and to store them into the cache so that they can provide the cache each time they are requested.
Hibernate support caching at two levels:-
- First Level Caching
- Second Level Caching
First Level Caching:-(Transactional scope caching)
First level caching is implicitly enable. It is implemented by session. First level caching is responsible for storing the object used by user. Object in this cache has transactional scope, once the transaction is completed object of this cache are synchronize to the database and cache is discarded.
Second Level Cache :-(Application Scope caching)
Second level cache is not enable by default. This cache has a application scope, Object in this cache are shared by multiple users. This cache is managed by sessionFactory
Caching is all about application performance optimization and it sits between your application and the database to avoid the number of database hits as many as possible to give a better performance for performance critical applications.
Caching is important to Hibernate as well which utilizes a multilevel caching schemes as explained below:
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.
Hibernate does not provide implementation of Second level caching , it only provide specification how second level cache should be implemented. Third party implementation of second level cache are available:
- EHCACHE ( Easy hibernate Caching)
- OSCACHE (Open source caching)