What is Caching in Hibernate

Caching functionality is designed to reduce the amount of necessary database access. When the objects that are cached reside in memory. You have the flexibility to limit the usage of memory and store the items in disk storage. The implementation will depend on the underlying cache manager. There are various flavors of caching available, but it is better to cache non-transactional and read-only data.

Hibernate provides 3 types of caching.

  1. Session Cache
  2. Second Level Cache
  3. Query Cache

Session Cache

The session cache caches objects within the current session. It is enabled by default in Hibernate. Read more about Session Cache. Objects in the session cache reside in the same memory location.

Second Level Cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also.

Second Level Cache implementations are provided by different vendors such as:

  • EH (Easy Hibernate) Cache from hibernate framework
  • Swarm Cache
  • Open Symphony Cache from Open Symphony
  • TreeCache from JBoss Cache

Query Cache

Query Cache is used to cache the results of a query. Read here on how to implement query cache. When the query cache is turned on, the results of the query are stored against the combination query and parameters. Every time the query is fired the cache manager checks for the combination of parameters and query. If the results are found in the cache, they are returned, otherwise a database transaction is initiated. As you can see, it is not a good idea to cache a query if it has a number of parameters, because then a single parameter can take a number of values. For each of these combinations the results are stored in the memory. This can lead to extensive memory usage.