Hibernate Query


Hibernate Cache System

Hibernate came with an innovative way to fetch the data from a database quicker via the simple caching technique to match up with the pace of the fast-moving world. Cache is a memory cache that connects an application to the site layer to store recently used data. Caching saves time as the applications do not have to go and hit the database server to fetch the data from tables as it is readily present in the cache. This process improves system performance by reducing the time to download the most widely used data.

Query-level Cache

Hibernate uses a multilevel caching technique called first level and second level caching. An optional cache, known as query-level cache, requires more physical cache memory to be added to the setup. Suppose we have some complex data-intensive queries running at the regular interval of times that need to fetch data using the same parameters. In that case, we can have this cache added to our system to fasten the query results as these results will be stored already in the query cache.

You first need to activate the query cache to use it using: hibernate. cache.use_query_cache=” true” property in the configuration file.
Setting this property to true makes Hibernate create the necessary caches in memory to hold the query and identifier sets.

For example:

Session session = SessionFactory.openSession();
Query query = session.createQuery("FROM EMPLOYEE");
query.setCacheable(true);
List users = query.list();
SessionFactory.closeSession();