Use Query Caching in Hibernate Cache
Hibernate Query Caching improves performance by caching query results so that frequently executed queries with the same parameters can reuse cached results instead of repeatedly accessing the database. Please note that any object retrieved as a result of the query is cached to its respective region. Therefore, mark objects as cacheable for efficient use of query caching.
Important
Hibernate versions up to 5.2 use a default query cache region for storing cached query results. In Hibernate 5.2, the StandardQueryCache implementation is org.hibernate.cache.internal.StandardQueryCache.
Note
Since not every query's results remain the same for a period of time, use query caching with queries whose results are less likely to change frequently.
Enable Query Caching in Hibernate Cache
To enable query caching in Hibernate, add the following property to the session-factory section of hibernate.cfg.xml.
<hibernate-configuration>
<session-factory>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">com.alachisoft.ncache.NCacheRegionFactory</property>
<property name="ncache.application_id">myapp</property>
<property name="hibernate.cache.use_query_cache">true</property>
</session-factory>
</hibernate-configuration>
Enabling the Hibernate query cache does not cache every query by default. Queries that need to be cached must be explicitly marked as cacheable in the application code. To set a query as cacheable, call the setCacheable(true) function of the query while creating a query. The code below is an example showing a cacheable query in Hibernate cache:
var session = sessionFactory.openSession();
ArrayList<Products> productList = (ArrayList<Products>) session.createQuery("from Products p", Products.class).setCacheable(true).list();
for (var product : productList) {
System.out.println("Retrieved Product: " + product);
}
session.close();
See Also
Hibernate First Level Cache
Configure Cacheable Objects and Regions
Configure Hibernate Application