Use Query Caching
Query caching makes use of L2 cache to store queries, so that whenever the same query is needed to be executed again, it can be fetched from the cache. Please note that any object retrieved as a result of query are cached to their respective regions, therefore objects must be marked as cacheable for efficient use of query caching. However query along with the primary keys of result sets is stored in a default query region named as a fully qualified name of hibernate's StandardQueryCache class "org.hibernate.cache.StandardQueryCache".
Note
Since not every query's results remain the same for a period of time,therefore query caching should only be used with queries whose results are less likely to be changed frequently.
To enable query caching, add the following tag to your configuration in hibernate.cfg.xml.
<hibernate-configuration>
<session-factory>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">JCacheRegionFactory</property>
<property name="ncache.application_id">myapp</property>
<property name="hibernate.cache.use_query_cache">true</property>
</session-factory>
</hibernate-configuration>
Enabling query cache does not cache each query by default. Instead queries needed to be cached are to be set cacheable in code. To set a query cacheable, call setCacheable(true)
function of query while creating query.The code below is an example showing a cacheable query:
try
{
List customerEnumerator = session.createQuery("from Customer c").setCacheable(true).list();
List customers = new ArrayList();
Transaction tx = null;
if (!session.isConnected())
{
session = factory.openSession();
}
tx = session.beginTransaction();
for (Customer customer : (List<Customer>) customerEnumerator)
{
customers.add(customer);
}
tx.commit();
}
catch (Exception ex)
{
tx.rollback();
session.clear();
session.disconnect();
throw ex;
}
See Also
Initialize Cache
Add/Update in Cache
Hibernate First Level Cache
Configure Cacheable Objects and Regions
Configure Hibernate Application